I executed a background process that was obtained as a parameter and didn't success to get the process's name after the execution.
I do the following:
#! /bin/bash
filePath=$1
$filePath > log.txt &
echo `jobs -l`
Actual result:
[1]+ 2381 Running $filePath > log.txt &
Expected result:
[1]+ 2381 Running /home/user/Desktop/script.sh > log.txt &
The best answer is don't; job control is a feature designed for interactive use, and is not guaranteed to be available at all in noninteractive shells, much less guaranteed to behave in any useful or meaningful way. However, if you insist, you can use printf %q
to generate an eval
-safe string with the post-expansion form of your variables, and then use eval
to run it as code:
#!/bin/bash
printf -v logfile_q '%q' "${log:-log.txt}" # use "$logfile", or default to log.txt
printf -v cmd_q '%q ' "$@" # quote our arguments into one eval-safe string
eval "$cmd_str >$logfile_q &" # Parts that aren't hardcoded must be printf-q'd for safety.
jobs -l
Note that I added some extra configurability for the sake of demonstration -- it's okay to have >log.txt
inside your eval
'd code, but it's not safe to have >$logfile
, because if logfile=$'foo$(rm -rf ~)\'$(rm -rf ~)\''
(a perfectly legal filename!) then you're going to lose your home directory. Thus, any variables needing to be used inside an argument to eval
need to be escaped with printf %q
beforehand.