Issue
I am new to shell scripting. I have saved the script file as script_hdl in my home directory. From my home directory, I want to navigate using the script in the following order: cd ../../site/edu/ess/project/user/rark444
and then open a new tab from this new location in the terminal.
I used this as my script:
#!/bin/bash
alias script_hdl="cd ../../site/edu/ess/project/user/rark444"
I run the script like this
./script_hdl
But I don't see any response in the terminal. I feel I am missing something but I don't know what is it. Thanks in advance for your help.
Solution
You have two ways to change directory here.
Script
The first one is to write a script, in such a way that you can run other command after cd
. It works without the alias
command: let's say you remove it.
cd
command is proper to the running process. When you execute your script, the following happen:
- your shell spawns (forks as) a new shell process executing your code. The main process wait for its child to finish;
- this new child process actually does change its own working directory with your
cd
command, then quits (it's over) - the original shell process stops waiting and prints the prompt again. But this process has not changed directory (only the child process did)
To perform what you want, (remove the alias
command, then) call your script as follows:
source script_hdl
or with following shortcut:
. script_hdl
meaning that you want the instructions to run in the same shell process.
Alias
The second way to change directory is to use an alias. But you should not write your alias definition in a random script file, add it in your ~/.bashrc
instead (this file is run each time you open a shell).
So:
alias script_hdl="cd ../../site/edu/ess/project/user/rark444"
to reload ~/.bashrc
:
. ~/.bashrc
And then don't try to execute from the file, just launch your alias as if it was a normal command:
script_hdl
Answered By - Qeole Answer Checked By - David Goodson (WPSolving Volunteer)