Skip to content
loading...

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

twitter logo github logo ・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

twitter logo DISCUSS
Classic DEV Post from Jun 17 '19

Should a button communicate the current state, the intended behavior, or both?

When I magnify a window in Chrome, I see an icon like this: When I reduce the size of a window bel...

Cristian profile image
Rubyist / Software Engineer