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.
1 Answer
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.
3 Comments
Anderson Green
I found this question that led me to believe that it wasn't possible to use cd in a shell script: stackoverflow.com/questions/255414/…
Anderson Green
So would it be better to use an alias (as suggested in the question above), or to simply use the cd command?
kev
bash will start a subshell to run your script which cannot change directory of its parent shell.
ls /home?