How to execute a command saved in a variable in linux and save the result in a new variable

41 views Asked by At

I am executing a series of commands and I hope to achieve the following effect:

  1. I need to echo the command before the execution.
  2. Execute the command and save the results to a bash variable, including incorrect results.
  3. Obtain execution results and execution status to determine whether subsequent commands need to be executed

Similar to the following:

  • cmd_var.sh
#!/bin/bash

log(){
  echo "$(date +"[%Y%m%d %H:%M:%S]:")" "$@"
}

grep_proc_cmd="ps -ef | grep endless_loop.sh | grep -v grep"
log "exec command: $grep_proc_cmd"
exec_ret=$($grep_proc_cmd 2>&1)

if [ $? != 0 ];then
  log "exec failed: $exec_ret"
  exit 1
fi
log "exec successfully: ret: [$exec_ret]"
  • Actual

The error reported when executing the above script is as follows:

$ bash var_cmd.sh 
[20240301 01:56:26]: exec command: ps -ef | grep endless_loop.sh | grep -v grep
[20240301 01:56:26]: exec failed: error: garbage option

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.



For more details see ps(1).
  • Expect

The result of executing the command variable in the terminal is stored in the result variable(in exec_ret).

[20240301 01:56:26]: exec command: ps -ef | grep endless_loop.sh | grep -v grep
[20240301 01:56:26]: exec successfully: ret: [ec2user      20384 4185646  0 01:53 pts/16   00:00:00 bash endless_loop.sh]

Please tell me how to achieve the desired effect, and further, whether there is a situation where the variable saving command is applicable to all variables.

Such as:

kill_cmd="ps -ef | grep A | grep -v grep | awk '{print \$2}' | xargs sudo kill -9"

cp_cmd="cp A B"
  • other way
#!/bin/bash

grep_proc_func(){
  log "exec: ps -ef | grep endless_loop.sh | grep -v grep"
  exec_ret=$(ps -ef | grep endless_loop.sh | grep -v grep 2>&1)
  exec_status=$?
}

main(){
  grep_proc_func
  if [ "$exec_status" != 0 ];then
    log "exec failed: $exec_ret"
    exit 1
  fi
  log "exec successfully: ret: $exec_ret"

  # other cmd function
}

main "$@"
0

There are 0 answers