Skip to content

Instantly share code, notes, and snippets.

@adamelliotfields
Created July 12, 2024 12:21
Show Gist options
  • Save adamelliotfields/36107117678129f260e8f4aba54b92b4 to your computer and use it in GitHub Desktop.
Save adamelliotfields/36107117678129f260e8f4aba54b92b4 to your computer and use it in GitHub Desktop.
Maintain Relative Paths in Shell Scripts

You can use the $0 variable to get the script's path:

cat "$(dirname $0)/some/file.txt"

If you have Bash, you can use ${BASH_SOURCE[0]} instead of $(dirname $0), to avoid spawning a subshell. To test, create 2 files in /tmp/test:

mkdir -p /tmp/test

# quote to prevent variable expansion
cat <<'EOF' > /tmp/test/start.sh
#!/usr/bin/env bash
script_dir="${BASH_SOURCE[0]%/*}"
echo "Running start.sh from: $(pwd)"
echo "Script directory is: $script_dir"
"$script_dir"/launch.py
EOF

cat <<EOF > /tmp/test/launch.py
#!/usr/bin/env python3
import os
print(f"Running launch.py from: {os.getcwd()}")
print(f"Script is: {os.path.abspath(__file__)}")
EOF

chmod +x /tmp/test/start.sh /tmp/test/launch.py

Now cd ~ and run /tmp/test/start.sh and you should see:

Running start.sh from: /home/adam
Script directory is: /tmp/test
Running launch.py from: /home/adam
Script is: /tmp/test/launch.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment