- Linux / Unix Shell Script: Get The Current Directory
- Syntax
- Shell script example
- How can I get the current working directory? [duplicate]
- 5 Answers 5
- Change the current directory from a Bash script
- 17 Answers 17
- file 1: outer.sh
- file 2: inner.sh
- How can I set the current working directory to the directory of the script in Bash?
- 13 Answers 13
- For all UNIX/OSX/Linux
- Unix shell script find out which directory the script file resides?
- 17 Answers 17
Linux / Unix Shell Script: Get The Current Directory
I am working on a shell script. I need to find out the current working directory. How do I get the current working directory under Bash or Ksh shell running on Linux or Unix like operating systems?
You can use shell variable called PWD or pwd built-in command to get the current working directory. The cd command sets the following shell variable:
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash/Ksh |
Est. reading time | N/A |
Syntax
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Shell script example
The following script use $PWD twice to set default and provide information to the sys admins.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How can I get the current working directory? [duplicate]
I want to have a script that takes the current working directory to a variable. The section that needs the directory is like this dir = pwd . It just prints pwd how do I get the current working directory into a variable?
5 Answers 5
There’s no need to do that, it’s already in a variable:
The PWD variable is defined by POSIX and will work on all POSIX-compliant shells:
Set by the shell and by the cd utility. In the shell the value shall be initialized from the environment as follows. If a value for PWD is passed to the shell in the environment when it is executed, the value is an absolute pathname of the current working directory that is no longer than
bytes including the terminating null byte, and the value does not contain any components that are dot or dot-dot, then the shell shall set PWD to the value from the environment. Otherwise, if a value for PWD is passed to the shell in the environment when it is executed, the value is an absolute pathname of the current working directory, and the value does not contain any components that are dot or dot-dot, then it is unspecified whether the shell sets PWD to the value from the environment or sets PWD to the pathname that would be output by pwd -P. Otherwise, the sh utility sets PWD to the pathname that would be output by pwd -P. In cases where PWD is set to the value from the environment, the value can contain components that refer to files of type symbolic link. In cases where PWD is set to the pathname that would be output by pwd -P, if there is insufficient permission on the current working directory, or on any parent of that directory, to determine what that pathname would be, the value of PWD is unspecified. Assignments to this variable may be ignored. If an application sets or unsets the value of PWD, the behaviors of the cd and pwd utilities are unspecified.
For the more general answer, the way to save the output of a command in a variable is to enclose the command in $() or ` ` (backticks):
Of the two, the $() is preferred since it is easier to build complex commands like:
Источник
Change the current directory from a Bash script
Is it possible to change current directory from a script?
I want to create a utility for directory navigation in Bash. I have created a test script that looks like the following:
When I execute the script from the Bash shell the current directory doesn’t change. Is it possible at all to change the current shell directory from a script?
17 Answers 17
When you start your script, a new process is created that only inherits your environment. When it ends, it ends. Your current environment stays as it is.
Instead, you can start your script like this:
The . will evaluate the script in the current environment, so it might be altered
/bin I use them to know what is what 🙂
You need to convert your script to a shell function:
The reason is that each process has its own current directory, and when you execute a program from the shell it is run in a new process. The standard «cd», «pushd» and «popd» are builtin to the shell interpreter so that they affect the shell process.
By making your program a shell function, you are adding your own in-process command and then any directory change gets reflected in the shell process.
In light of the unreadability and overcomplication of answers, i believe this is what the requestor should do
- add that script to the PATH
- run the script as . scriptname
The . (dot) will make sure the script is not run in a child shell.
Putting the above together, you can make an alias
if you don’t want to write the leading «.» each time you want to source your script to the shell environment, or if you simply don’t want to remember that must be done for the script to work correctly.
/.bashrc file to make it persistent. Works like a charm for me.
/.bash_aliases is not always sourced when Bash launches.
If you are using bash you can try alias:
into the .bashrc file add this line:
when you write «p» on the command line, it will change the directory.
If you run a bash script then it will operates on its current environment or on those of its children, never on the parent.
If goal is to run your command : goto.sh /home/test Then work interactively in /home/test one way is to run a bash interactive subshell within your script :
This way you will be in /home/test until you exit ( exit or Ctrl+C ) of this shell.
With pushd the current directory is pushed on the directory stack and it is changed to the given directory, popd get the directory on top of the stack and changes then to it.
and add this code next to the last line:
Then quit editor.
now you can use: yourcommand in terminal
I’ve made a script to change directory. take a look: https://github.com/ygpark/dj
Basically we use cd.. to come back from every directory. I thought to make it more easy by giving the number of directories with which you need to come back at a time. You can implement this using a separate script file using the alias command . For example:
code.sh
After using source code.sh in the current shell you can use :
to come two steps back from the current directory. Explained in detail over here. It is also explained over there how to put the code in
/.bashrc so that every new shell opened will automatically have this new alias command. You can add new command to go to specific directories by modifying the code by adding more if conditions and different arguments. You can also pull the code from git over here.
Add below cd line in your shellscript this:
This approach is easier for me.
Suppose on a personal iMac where you are an admin, under the default directory when a command window is opened, /Users/jdoe, this will be the directory to go to: /Users/jdoe/Desktop/Mongo/db.3.2.1/bin.
These are the steps that can have the job done:
- vi mongobin, in which I entered: cd /Users/jdoe/Desktop/Mongo/db.3.2.1/bin as the first line.
- chmod 755 mongobin
- source mongobin
- pwd
I’ve also created a utility called goat that you can use for easier navigation.
You can view the source code on GitHub.
As of v2.3.1 the usage overview looks like this:
I like to do the same thing for different projects without firing up a new shell.
Save the_script as:
Then fire it up with:
Then you get to the directory using the same shell.
Declare your path:
This is my current way of doing it for bash (tested on Debian). Maybe there’s a better way:
Don’t do it with exec bash, for example like this:
because while it appears to work, after you run it and your script finishes, yes you’ll be in the correct directory, but you’ll be in it in a subshell, which you can confirm by pressing Ctrl+D afterwards, and you’ll see it exits the subshell, putting you back in your original directory.
This is usually not a state you want a script user to be left in after the script they run returns, because it’s non-obvious that they’re in a subshell and now they basically have two shells open when they thought they only had one. They might continue using this subshell and not realize it, and it could have unintended consequences.
If you really want the script to exit and leave open a subshell in the new directory, it’s better if you change the PS1 variable so the script user has a visual indicator that they still have a subshell open.
Here’s an example I came up with. It is two files, an outer.sh which you call directly, and an inner.sh which is sourced inside the outer.sh script. The outer script sets two variables, then sources the inner script, and afterwards it echoes the two variables (the second one has just been modified by the inner script). Afterwards it makes a temp copy of the current user’s
/.bashrc file, adds an override for the PS1 variable in it, as well as a cleanup routine, and finally it runs exec bash —rcfile pointing at the .bashrc.tmp file to initialize bash with a modified environment, including the modified prompt and the cleanup routine.
After outer.sh exits, you’ll be left inside a subshell in the desired directory (in this case testdir/ which was entered into by the inner.sh script) with a visual indicator making it clear to you, and if you exit out of the subshell, the .bashrc.tmp file will be deleted by the cleanup routine, and you’ll be back in the directory you started in.
Maybe there’s a smarter way to do it, but that’s the best way I could figure out in about 40 minutes of experimenting:
file 1: outer.sh
file 2: inner.sh
and then drop you into your subshell using exec bash, but with a modified prompt which makes that obvious, something like:
and if you Ctrl-D out of the subshell, it should clean up by deleting a temporary .bashrc.tmp file in the testdir/ directory
I wonder if there’s a better way than having to copy the .bashrc file like that though to change the PS1 var properly in the subshell.
Источник
How can I set the current working directory to the directory of the script in Bash?
I’m writing a Bash script. I need the current working directory to always be the directory that the script is located in.
The default behavior is that the current working directory in the script is that of the shell from which I run it, but I do not want this behavior.
13 Answers 13
The following also works:
The syntax is thoroughly described in this StackOverflow answer.
Try the following simple one-liners:
For all UNIX/OSX/Linux
Note: A double dash (—) is used in commands to signify the end of command options, so files containing dashes or other special characters won’t break the command.
Note: In Bash, use $
For Linux, Mac and other *BSD:
Note: realpath should be installed in the most popular Linux distribution by default (like Ubuntu), but in some it can be missing, so you have to install it.
Note: If you’re using Bash, use $
Otherwise you could try something like that (it will use the first existing tool):
For Linux specific:
Using GNU readlink on *BSD/Mac:
Note: You need to have coreutils installed (e.g. 1. Install Homebrew, 2. brew install coreutils ).
In bash
In bash you can use Parameter Expansions to achieve that, like:
but it doesn’t work if the script is run from the same directory.
Alternatively you can define the following function in bash:
This function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWD variable + filename argument (without ./ prefix).
or here is the version taken from Debian .bashrc file:
Источник
Unix shell script find out which directory the script file resides?
Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script file resides?
17 Answers 17
In Bash, you should get what you need like this:
The original post contains the solution (ignore the responses, they don’t add anything useful). The interesting work is done by the mentioned unix command readlink with option -f . Works when the script is called by an absolute as well as by a relative path.
For bash, sh, ksh:
An earlier comment on an answer said it, but it is easy to miss among all the other answers.
When using bash:
Assuming you’re using bash
This script should print the directory that you’re in, and then the directory the script is in. For example, when calling it from / with the script in /home/mez/ , it outputs
Remember, when assigning variables from the output of a command, wrap the command in $( and ) — or you won’t get the desired output.
If you’re using bash.
One-liner which will give you the full directory name of the script no matter where it is being called from.
To understand how it works you can execute the following script:
As theMarko suggests:
This works unless you execute the script from the same directory where the script resides, in which case you get a value of ‘.’
To get around that issue use:
You can now use the variable current_dir throughout your script to refer to the script directory. However this may still have the symlink issue.
If you want to get the actual script directory (irrespective of whether you are invoking the script using a symlink or directly), try:
This works on both linux and macOS. I couldn’t see anyone here mention about realpath . Not sure whether there are any drawbacks in this approach.
on macOS, you need to install coreutils to use realpath . Eg: brew install coreutils .
Let’s make it a POSIX oneliner:
Tested on many Bourne-compatible shells including the BSD ones.
As far as I know I am the author and I put it into public domain. For more info see: https://www.jasan.tk/posts/2017-05-11-posix_shell_dirname_replacement/
INTRODUCTION
This answer corrects the very broken but shockingly top voted answer of this thread (written by TheMarko):
WHY DOES USING dirname «$0» ON IT’S OWN NOT WORK?
dirname $0 will only work if user launches script in a very specific way. I was able to find several situations where this answer fails and crashes the script.
First of all, let’s understand how this answer works. He’s getting the script directory by doing
$0 represents the first part of the command calling the script (it’s basically the inputted command without the arguments:
dirname basically finds the last / in a string and truncates it there. So if you do:
you’ll get: /usr/bin
This example works well because /usr/bin/sha256sum is a properly formatted path but
wouldn’t work well and would give you:
Say you’re in the same dir as your script and you launch it with this command
$0 in this situation will be ./script and dirname $0 will give:
Without inputting the full path will also give a BASEDIR=».»
Using relative directories:
Gives a dirname $0 of:
If you’re in the /some directory and you call the script in this manner (note the absence of / in the beginning, again a relative path):
You’ll get this value for dirname $0:
and ./path/./script (another form of the relative path) gives:
The only two situations where basedir $0 will work is if the user use sh or touch to launch a script because both will result in $0:
which will give you a path you can use with dirname.
THE SOLUTION
You’d have account for and detect every one of the above mentioned situations and apply a fix for it if it arises:
Источник