DEV Community

loading...

To cd or not to cd...in a shell script?

cristian profile image Cristian ・1 min read

In a few cases, I've noticed the use of cd in shell scripts, and this practice never really made sense to me. It seems so broken to change the current working directory to perform a command in a given context, such as another directory. I think using cd seems broken to me because it opens up the door that you might forget to cd back to the original directory if needed.

What do you think?

Bad?

#!/usr/bin/env bash

set -euo pipefail

EASYRSA_PATH='/etc/openvpn/easy-rsa'

cd $EASYRSA_PATH

./easyrsa init-pki

# other commands unrelated to EASYRSA_PATH

Good?

#!/usr/bin/env bash

set -euo pipefail

EASYRSA_PATH='/etc/openvpn/easy-rsa'

"${EASYRSA_PATH}/easyrsa" init-pki

# other commands unrelated to EASYRSA_PATH

Discussion

pic
Editor guide