'Can cd commands be used multiple times in a script?
I am writing a script , please confirm if I can use multiple cd commands as I have to create and cd multiple times to make the job run. So can I use it again and again.
I have created a small script from it to mkdir and cd in one command but its not working .
1.
function mkdircd () { mkdir -p testjdk && eval cd "$_" ; }
mkdircd /tmp/testjdk
pwd
mkdir test && cd "$_"
However 2nd one works outside if I directly tried to run it but inside the script its not working .
Solution 1:[1]
I am assuming you want a bash script to make a directory and then cd into it? Something similar to what is shown below will work.
You need to pass an argument to the function and to the script itself. So $1 is the argument that you pass to the Function call when you run the script from the command line. And then within the script then the same argument is passed to the function.
So say this script was named test.sh, then you would run it by executing something like source test.sh ./my_dir. Here ./my_dir is the relative path to the directory that you want to create and enter. If you want to create and enter it in the root then run the script with sudo and specify the full path.
#!/bin/bash
#It is a function
myFunction() {
mkdir -p $1;
cd $1
}
#function call
myFunction $1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DharmanBot |
