简体   繁体   中英

Create and execute a shell script in Linux home directory

I would like to create (and execute) a shell script in my home directory (/home/user).

Have tried the following:

printf "cd /mypath\n" > myShortcut.sh
chmod +x myShortcut.sh
sh myShortcut.sh

where am I going wrong?

(am trying to set up a shortcut to navigate to a different directory)

What is exactly wrong here? That you are still in /home/user after the script executes? Well thats because executing the script creates a child shell that returns to the parent shell once the script ends. Therefore your cd has NO EFFECT in your current shell.

If you want to execute the script in the current shell (as opposed to in a subshell ), use the source (or . ) command:

 source myShortcut.sh

This should then change the directory as expected.

In addition, sourcing also allows you to set and change environment variables in the current shell--a very frequent question in its own right :-)

That won't work because of what the other answer says. The script operates in a child shell.

For a shortcut like that, you could set up an alias, edit the .bashrc file in your home directory and add a line like

alias shortcut='cd /mypath'

Substitute "shortcut" for whatever you want to name it, and mypath to the path you want. Restart the shell (close terminal and reopen or w/e) and that should work just as you want. Then you can use "shortcut" anywhere you want in the shell.

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