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.

2
  • 1
    What's wrong with ls /home ? Commented Oct 17, 2012 at 3:14
  • I'm not too familiar with shell scripting - thanks for the suggestion! Commented Oct 17, 2012 at 3:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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/…
So would it be better to use an alias (as suggested in the question above), or to simply use the cd command?
bash will start a subshell to run your script which cannot change directory of its parent shell.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.