Issue
Why does this scrips falls into a loop when I source it (e.g. . cd.sh file:///home/user/pCloudDrive/courses/CCNA/CCNA_200-301_Official_Cert_Guide/Odom,_Wendell_-_CCNA_200-301_Official_Cert_Guide,_Volume_1.pdf
)?
#!/usr/bin/bash
#alias cd='. ~/CS/SoftwareDevelopment/MySoftware/Bash/cd/cd.sh
#when I do cd file:///home/user/pCloudDrive/courses/CCNA/CCNA_200-301_Official_Cert_Guide/Odom,_Wendell_-_CCNA_200-301_Official_Cert_Guide,_Volume_1.pdf
#it is supposed to do cd /home/user/pCloudDrive/courses/CCNA/CCNA_200-301_Official_Cert_Guide
dst_dr=$(echo "${1}"|sed -E 's,file://,,;s,/[^/]*\.pdf|/[^/]*\.PDF,,')
echo "$dst_dr"
export dst_dr
cd "$dst_dr"
The script outputs and does not stop:
/home/user/pCloudDrive/courses/CCNA/CCNA_200-301_Official_Cert_Guide
/home/user/pCloudDrive/courses/CCNA/CCNA_200-301_Official_Cert_Guide
/home/user/pCloudDrive/courses/CCNA/CCNA_200-301_Official_Cert_Guide
/home/user/pCloudDrive/courses/CCNA/CCNA_200-301_Official_Cert_Guide
I wrote it because frequently I have the need to cd to a directory of a pdf that I currently reading in my browser. The script is meant to give me the directory of such a pdf and cd to it.
Solution
Why does this scrips falls into a loop
You aliased cd
to sourcing the script.
When you execute cd
, the script is sourced.
The script executes cd
.
Which in turn sources the script again.
And the script executes cd
again.
Which sources the script again.
Which loops.
You can prefix the command with slash to execute without alias. You can use \cd
in your script to execute real cd
builtin.
You can prefix the command with command
to execute the real command or builtin, not an alias nor function. You can use command cd
in your script.
Aliasing cd
sounds confusing, and aliasing to sourcing sounds more confusing. I recommend using a function. I recommend naming the function (and alias) something unique, like mycd
or cdmy
, and leave poor cd
as it is.
Answered By - KamilCuk Answer Checked By - Mildred Charles (WPSolving Admin)