Issue
I want to write a script that lists all the files I have within a folder.
My try:
#!/bin/bash
if ! test -d "$1" ; then
echo `pwd`/$1
else
cd "$1"
for f in * ; do
"$0" "$f"
done
fi
I invoke: sh /home/user/test.sh folder
.
This script works only if I specify the absolute path of the script. I'm looking for a more general solution that works also if I specify the script relative path.
Solution
You can use the string-line solution inside the comments or write another script where you:
- pre-process the input
- add the full path
- then invoke the script
To do that, create another script test-rec.sh
:
#!/bin/bash
if test "$0" = /* ; then
echo "Absolute path"
rec_cmd="`dirname "$0"`/test.sh"
elif test "$0" = */* ; then
echo "Relative path"
rec_cmd="`pwd`/`dirname "$0"`/test.sh"
else
echo "Neither absolute or relative, I use the PATH"
rec_cmd="test.sh"
fi
"$rec_cmd" "$1"
to be invoked in the same way, through sh test-rec.sh folder
Answered By - Alez Answer Checked By - Terry (WPSolving Volunteer)