This is your code:
printf ("Creating swap file...", %)
fallocate -l 4G swapfile
if [ $? ]
echo "ok"
else
echo "failed"
fi
You are using printf
oddly. It's an ordinary shell command, so no parentheses are needed. Also, that trailing %
look out of place. In this case, and at that point in the code, you have nothing more to output other than a static string, so no format specifier is needed. So, yes, printf
is the proper command to use here, because it doesn't output a newline at the end of its output unless you tell it to.
If you'd just want to act on the exit status of fallocate
, then you may put the command in the if
-statement directly, like this:
printf "Creating swap file...\t"
if fallocate -l 4G swapfile; then
echo "ok"
else
echo "failed"
fi
If you have a pipeline, the exit status of the pipeline will be that of the last command in the pipeline:
if cmd1 | cmd2 | cmd3; then
# ...
fi
This is also true for compound commands like cmd;cmd
, {cmd;cmd}
, (cmd;cmd)
etc.
To have pipelines return the exit status of the last command in a pipeline that fails in bash
, you will need to set the pipefail
option:
set -o pipefail
To get at the exit statuses of the intermediate pipeline commands in bash
you may inspect the PIPESTATUS
array after executing the pipeline:
$ false | true | true | false
$ echo ${PIPESTATUS[@]}
1 0 0 1