Some remarks
1. 🟥🟥🟥 W A R N I N G ! ! ! 🟥🟥🟥
Comming late to this question, I have to see: no answer here address ShellCheck SC2164!!
Use cd ... || exit
in case cd
fails,
Explanation:
If you hit some mispelled path before doing some destructive command:
( cd /wrong/path ; rm -fR * )
then the cd
command will fail, but
subsequent command will anyway destroy everything in the current directory!!
So the correct command is
( cd /path/to/wherever || exit; mycommand ... )
(you could replace exit
by return
if in a function or continue
if in a loop),
or
( cd /path/to/wherever && mycommand ... )
2. RTFM
Before doing some more steps then required, maybe should you have a look at the man page of the command you plan to run!
There is a lot of commands, like tar
, wget
and others, which offer specific parameter for doing this:
$ man tar | grep -A3 ' --directory'
-C, --directory=DIR
Change to DIR before performing any operations. This option is
order-sensitive, i.e. it affects all options that follow.
So doing
( cd /some/path && tar -cpl somedir )
will do same than
tar -cplC /some/path somedir
3. Storing command's output into shell variables
For sample, trying to read result of find
command into some array
variable:
Instead of trying something like this:
( cd /some/path && var=$(du -chs .) )
( cd /some/path && mapfile -d '' -t array < <(find . -type f -print0 ) )
because none of your $var
or $array
won't exist outside of subshell (parenthesis).
but, you may run:
var=$( cd /some/path && du -chs . )
mapfile -d '' -t array < <( cd /some/path && find . -type f -print0 )
4. chroot
instead of just cd
:
Sometime,
Bash execute a command in a different (directory) context?
could mean in the context of a virtual machine that is not currently in running state, or in the context of a backuped host, in a specific backup or even else...
For sample, using lxc
you could show journal off a stopped container by running:
sudo chroot /var/lib/lxc/stoppedContainer/rootfs/ journalctl -ax
But in manual page, you may read that you could to (near) same by using --root
option of journalctl
:
sudo journalctl --root /var/lib/lxc/stoppedContainer/rootfs -ax
In fact, there are totally different commands, as
- in first sample using
chroot
, you will run the correct journalctl
command, that is installed in the container (/var/lib/lxc/stoppedContainer/rootfs/usr/bin/journalctl
),
- but the second sample will work only if the
journalctl
installed in the host (hardware node /usr/bin/journalctl
) is able to read container's journal data (version compatibility).