Friday, May 3, 2024
104
rated 0 times [  104] [ 0]  / answers: 1 / hits: 184264  / 3 Years ago, tue, july 27, 2021, 9:06:26

I just want to write a script which changes my directory.



I put the below commands in the file /home/alex/pathABC



#!/bin/sh
cd /home/alex/Documents/A/B/C
echo HelloWorld


I did



chmod +x pathABC


In the Terminal, while in /home/alex, I ran ./pathABC, but the output is just HelloWorld and the current directory is not changed.



So what is wrong?


More From » command-line

 Answers
0

As others have explained, the directory is changed in the child process of your script, not in the terminal process from which the script is called. After the child process dies, you are back in the terminal which is left where it was.



Several alternatives:



1. Symbolic link



Put a symlink in your home to the long path you want to easily access



$ ln -s /home/alex/Documents/A/B/C ~/pathABC


then access the directory with:



$ cd ~/pathABC


2. Alias



Put an alias in your ~/.bashrc:



alias pathABC="cd /home/alex/Documents/A/B/C"


(from here)



3. Function



Create a function that changes the directory, the function runs in the process of your terminal and can then change its directory.



(from here)



4. Avoid running as child



Source your script instead of running it. Sourcing (done by . or source) causes the script to be executed in the same shell instead of running in its own subshell.



$ . ./pathABC


(from here and here)



5. cd-able vars



Set the cdable_vars option in your ~/.bashrc and create an environment variable to the directory:



shopt -s cdable_vars
export pathABC="/home/alex/Documents/A/B/C"


Then you can use cd pathABC



(from here)


[#24696] Thursday, July 29, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
splenueak

Total Points: 448
Total Questions: 118
Total Answers: 110

Location: Vanuatu
Member since Mon, Oct 3, 2022
2 Years ago
;