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