简体   繁体   中英

Run a Bash script command in a specified folder

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM