Is there a way to store a filename in a variable where the variable argument is written? Instead of hardcoding the filename, i would want the variable to know which file its in and store the name of the file in a variable.
Asked
Active
Viewed 125 times
0
-
In `bash`, `$0` gives the name of the shell or shell script that is running, if that helps. – leekaiinthesky Feb 16 '17 at 02:13
-
Seems to be what I need but it displays filename the same way it was called; relative or absolute. How would this behave in cron? – Andy Feb 16 '17 at 02:54
-
@Andy why not try and find out :) – Karan Shah Feb 16 '17 at 04:13
1 Answers
1
dirname $0 will give the directory relative to how it was called, so you need to get the expanded path like this:
FULLPATH=$( cd $(dirname $0); pwd)
basename $0 will give the shell script name so
SHORTNAME=$(basename $0)
$FULLPATH/$SHORTNAME # is the fully qualified location of the current script.
The full path name is discussed as the most frequent bash question: Getting the source directory of a Bash script from within

Community
- 1
- 1

Mike Wodarczyk
- 1,247
- 13
- 18