DEV Community

Cristian
Cristian

Posted on

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

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Top comments (0)