In a Bash script, is it possible to run a command in a specific folder? For example, I'd like to create a script that prints the contents of the /home
folder using ls
, no matter which directory the script is saved in.
Asked
Active
Viewed 139 times
0

Anderson Green
- 30,230
- 67
- 195
- 328
-
1What's wrong with `ls /home` ? – cdarke Oct 17 '12 at 03:14
-
I'm not too familiar with shell scripting - thanks for the suggestion! – Anderson Green Oct 17 '12 at 03:15
1 Answers
1
Actually, you can use cd
to change directory in a script (but it'll not affect its parent shell). Try
#!/bin/bash
# myscript.sh
cd /home
pwd
ls
It'll print current directory (which is /home
) and list the content of it. No matter what location of myscript.sh
is.

kev
- 155,172
- 47
- 273
- 272
-
I found this question that led me to believe that it wasn't possible to use cd in a shell script: http://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script – Anderson Green Oct 17 '12 at 01:55
-
So would it be better to use an alias (as suggested in the question above), or to simply use the cd command? – Anderson Green Oct 17 '12 at 01:56
-
`bash` will start a subshell to run your script which cannot change directory of its parent shell. – kev Oct 17 '12 at 01:57