dimanche 16 décembre 2018

"cd" inside "if" condition in Bash does not change the current directory after "if"

I am trying to do "cd" inside "if" condition in a Bash script. It stays in the same directory after "if". So I have to do "cd" outside "if" and then use $? value in if. Is there a way to avoid using this extra step? What is the shortest possible way of doing it?

See three variants of my code:

#!/bin/bash

set +e

# If I write the following:

if ! (rm -rf sim && mkdir sim && cd sim); then
    echo $0: Cannot prepare simulation directory
    exit 1
fi

# it does not change the current directory

echo $PWD

# Also, if I write the following:

if ! rm -rf sim || ! mkdir sim || ! cd sim; then
    echo $0: Cannot prepare simulation directory
    exit 1
fi

# it also does not change the current directory

echo $PWD

# In order to change the current directory, I need to write:

rm -rf sim && mkdir sim && cd sim

if [ $? -eq 1 ]; then
    echo $0: Cannot prepare simulation directory
    exit 1
fi

# Now it prints .../sim

echo $PWD
cd ..

# Is it possible to write it without an additional line with $?

exit

Aucun commentaire:

Enregistrer un commentaire