The problem is that I wrote a bash script that handle files. If I add this script to bashrc I can't find the file. I could write the absolute path but I would like to compress the directory and send it to others. It could be so bad if no one could use my script because the path. The project looks like: DIR A
- Script
- ReadMe
- DIR B
- Python Script
- File
The Script call the Python script and the Python script read from the File. I would like to call the Script as an enviroment variable from anywhere but I can't because it can't find the Python script and the file. Is there a way to call the script like it is in the directory next to DIR B? Like a realpath or I don't know. I'm not really good at this. :( Thank you so much!
CodePudding user response:
chmod x my_script.sh # make it executable
# create a link in your bin folder
sudo ln -s /usr/local/bin/my_script.sh $(pwd)/my_script.bat
youll want to make sure your script starts with the shebang
#! /bin/bash
finally invoke it as just
$ my_script.sh some arguments 5
instead of
$ . my_script.sh
or
$ source my_script.sh
you can create an install method to do all of these steps for other users of your program ...
but this sounds sort of like an x/y problem (ie this does what your question asks, but maybe doesnt solve your underlying problem)
CodePudding user response:
If the bash-script is sourced, it is always
scriptname=$(realpath "$BASH_SOURCE")
Therefore, the directory of the sourced bash-script is always
dir=$(dirname "$scriptname")
A simple
cd "$dir"
before calling the python script would do the trick.
Note, that if you do not source the script, "$BASH_SOURCE"
will be empty. You can test for this to make sure that the script is sourced:
if [ "$BASH_SOURCE" = "" ] ; then
echo "This script should be sourced, not executed"
fi
CodePudding user response:
I think I've solved the problem. It's not so elegant, but it works. I don't want to use "cd" because I think it's a little bit ugly to cd to folders cd back...
In the bash script I use the dirname $0
to get the script path and concatenate with the other path of files like:
path=`dirname $0`
scriptpath="$path/dirB/python.py"
filepath="$path/dirB/file"
I gave the $filepath to the python script as an argument and it works like: (in the script call python function)
python3 $scriptpath $filepath $@
And I can read the file in the Python script like:
f = open(sys.argv[1], "r")
Thank you for all the answers! Have a beautiful day!