0

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.

Anderson Green
  • 25,996
  • 59
  • 164
  • 297

1 Answers1

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
  • 137,128
  • 36
  • 241
  • 259
  • 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