- HowTo: Use pwd Command In Linux / UNIX
- The current directory
- Syntax
- Examples
- A typical Linux/Unix shell session with pwd
- Shell pwd vs /bin/pwd
- pwd options
- /bin/pwd options
- BASH command output to the variable
- Command Substitution Syntax:
- Single command output to a variable
- Example#1:
- Example#2:
- Example#3:
- Example#4:
- Using command substitution in loop
- Example#5:
- Using nested commands
- Example#6:
- Using Command path
- Example#7:
- Using Command Line argument
- Example#8:
- Conclusion:
- About the author
- Fahmida Yesmin
- Linux and Unix pwd command tutorial with examples
- Tutorial on using pwd, a UNIX and Linux command for printing the name of the current working directory. Examples of printing the current working directory, avoiding symlinks and how to get the current working directory in shell scripts.
- Table of contents
- What is the pwd command in UNIX?
- How to print the current working directory
- How to avoid symlinks
- pwd is normally a shell builtin
- How to reference pwd in shell scripts
- Further reading
- Recent Posts
- About the author
- Команда pwd Linux
- Команда pwd в Linux
- Выводы
HowTo: Use pwd Command In Linux / UNIX
=> Find the full path to the current directory.
=> Store the full path to the current directory in the shell variable.
=> Verify the absolute path.
=> Verify the physical path i.e exclude symbolic links.
The current directory
The current directory is nothing but the directory in which you are currently operating while using bash or ksh or zsh or tcsh/csh shell. You need to open a terminal (GUI) or login on a console to use a command line.
Syntax
Examples
To print current working directory, enter:
$ pwd
Sample outputs:
In this example, /home/vivek is your current directory. The full path of any directory under Unix like operating systems always stats with a forward slash. In short:
- / – Forward slash – The root directory on your system or the file system.
- home – Sub-directory
- vivek – Sub-directory
To store current directory in a shell variable called x, enter:
To print the current directory either use printf command or echo command:
A typical Linux/Unix shell session with pwd
Most Unix users use the pwd command along with ls and cd commands:
Fig.01: A typical shell user session with pwd, ls, and cd commands.
Shell pwd vs /bin/pwd
Your shell may have its own version of pwd, which usually supersedes the version described below. To see all locations containing an executable named pwd, enter:
$ type -a pwd
Sample outputs:
- 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 ➔
By typing pwd, you end up using the shell builtin provided by bash or ksh:
pwd
To use the binary version, type full path /bin/pwd:
/bin/pwd
Please note that both commands print the current/working directory. However, /bin/pwd has few more options as described below.
pwd options
To display the logical current working directory, enter:
$ pwd -L
The -L option cause pwd to use $PWD from environment, even if it contains symlinks. If the contents of the environment variable PWD provide an absolute name of the current directory with no . or .. components, but possibly with symbolic links, then output those contents. Otherwise, fall back to default -P handling:
$ pwd -P
Display the physical current working directory (all symbolic links resolved). For example,
/bin/ is symbolic link:
$ pwd
$ ls -l
/bin/
Sample outputs:
/bin/ and verify the current working directory with pwd:
$ cd
/bin/
$ pwd
Sample outputs:
/home/vivek/bin
To see actual physical current working directory and avoid avoid all symlink called /home/vivek/bin, enter:
$ pwd -P
Sample outputs:
/bin/pwd options
The /bin/pwd version of pwd command has a two more additional options. To display pwd command version, enter:
$ /bin/pwd —version
Sample outputs:
Источник
BASH command output to the variable
Different types of bash commands need to be run from the terminal based on the user’s requirements. When the user runs any command from the terminal then it shows the output if no error exists otherwise it shows the error message. Sometimes, the output of the command needs to be stored in a variable for future use. Shell command substitution feature of bash can be used for this purpose. How you can store different types of shell commands into the variable using this feature is shown in this tutorial.
Command Substitution Syntax:
***Note: Don’t use any space before and after the equal sign when using the above commands.
Single command output to a variable
Bash commands can be used without any option and argument for those commands where these parts are optional. The following two examples show the uses of simple command substitution.
Example#1:
bash `date` command is used to show the current date and time. The following script will store the output of `date` command into $current_date variable by using command substitution.
Output:
Example#2:
`pwd` command shows the path of the current working directory. The following script stores the output of `pwd` command into the variable, $current_dir and the value of this variable is printed by using `echo` command.
Output:
Command with option and argument
The option and argument are mandatory for some bash commands. The following examples show how you can store the output of the command with option and argument into a variable.
Example#3:
Bash `wc` command is used to count the total number of lines, words, and characters of any file. This command uses -c, -w and -l as option and filename as the argument to generate the output. Create a text file named fruits.txt with the following data to test the next script.
fruits.txt
Run the following commands to count and store the total number of words in the fruits.txt file into a variable, $count_words and print the value by using `echo` command.
Output:
Example#4:
`cut` is another bash command that uses option and argument to generate the output. Create a text file named weekday.txt with seven-weekday names to run the next script.
weekday.txt
Create a bash file named cmdsub1.sh with the following script. In this script, while loop is used to read the content of weekday.txt file line by line and read the first three characters of each line by using `cut` command. After cutting, the string value is stored in the variable $day. Next, If the statement is used to check the value of $day is ‘Sun’ or not. The output will print ‘Sunday is the holiday‘ when if the condition is true otherwise it will print the value of $day.
cmdsub1.sh
Output:
Using command substitution in loop
You can store the output of command substitution into any loop variable which is shown in the next example.
Example#5:
Create a file named cmdsub2.sh with the following code. Here, `ls -d */` command is used to retrieve all directory list from the current directory. For loop is used here to read each directory from the output and store it in the variable $dirname which is printed later.
cmdsub2.sh
Output:
Using nested commands
How you can use multiple commands using pipe(|) is shown in the previous example. But you can use nested commands in command substitution where the output of the first command depends on the output of the second command and it works opposite of the pipe(|) command.
Nested command syntax:
Example#6:
Two commands, `echo` and `who` are used in this example as the nested command. Here, `who` command will execute first that print the user’s information of the currently logged in user. The output of the `who` command will execute by `echo` command and the output of `echo` will store into the variable $var. Here, the output of `echo` command depends on the output of `who` command.
Output:
Using Command path
If you know the path of the command then you can run the command by specifying the command path when using command substitution. The following example shows the use of command path.
Example#7:
`whoami` command shows the username of the currently logged in user. By default, this command is stored in /usr/bin/ folder. Run the following script to run `whoami` command using path and store in the variable, $output, and print the value of $output.
Output:
Using Command Line argument
You can use the command line argument with the command as the argument in the command substitution.
Example#8:
Create a bash file named cmdsub3.sh with the following script. `basename` command is used here to retrieve the filename from the 2 nd command line argument and stored in the variable, $filename. We know the 1 st command line argument is the name of the executing script which is denoted by $0.
Run the script with the following argument value.
Here, the basename of the path, Desktop/temp/hello.txt is ‘hello.txt’. So, the value of the $filename will be hello.txt.
Output:
Conclusion:
Various uses of command substitutions are shown in this tutorial. If you need to work with multiple commands or depended commands and store the result temporary to do some other tasks later then you can use this feature in your script to get the output.
More info in the video:
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.
Источник
Linux and Unix pwd command tutorial with examples
Tutorial on using pwd, a UNIX and Linux command for printing the name of the current working directory. Examples of printing the current working directory, avoiding symlinks and how to get the current working directory in shell scripts.
Estimated reading time: 3 minutes
Table of contents
What is the pwd command in UNIX?
The pwd command is a command line utility for printing the current working directory. It will print the full system path of the current working directory to standard output. By default the pwd command ignores symlinks, although the full physical path of a current directory can be shown with an option. The pwd command is normally a shell builtin meaning it is part of the code that runs the shell rather than an external executable.
How to print the current working directory
To print the current working directory run the pwd command. The full path of the current working directory will be printed to standard output.
How to avoid symlinks
To avoid symlinks pass the -P option. This will cause pwd to show the physical location rather than a symlink. To demonstrate this the following example shows a folder that is symlinked to another location. Without the -P option the symlink is ignored. In the following example the folder zsh is a symlink.
Running pwd within the zsh folder does not show the symlink.
Running pwd with the -P shows the physical location.
pwd is normally a shell builtin
In most shells pwd is a shell builtin. This means the command is present in the shell rather than calling an external program. This means that the code will run significantly faster than calling an external executable.
Whilst most shells have pwd as a shell builtin the command also exists on systems as an executable. On my own system the executable is located at /bin/pwd .
How to reference pwd in shell scripts
In most shells the $PWD variable is available and is set each time a user or in script changes directory. As such this variable can be referenced to show the current working directory.
Although $PWD is ubiquitous it is specific to the shell running the command so some prefer to reference the pwd command and store it in a variable. This makes scripts more portable as they will call the system executable if the shell builtin or the $PWD variable does not exist.
Althought the $PWD variable is present is almost all shells it is possible it may not be there. If you are really paranoid use CWD=$(pwd) but in most cases $PWD will work.
Further reading
Have an update or suggestion for this article? You can edit it here and send me a pull request.
Recent Posts
About the author
George Ornbo is a UK based human.
He is interested in people, music, food and writing. In a previous version of himself he wrote books on technology.
Источник
Команда pwd Linux
Команда pwd — это очень простая утилита, которая позволяет вывести в терминал путь к текущей папке. Каждая программа при запуске получает текущую папку в которой будут выполнятся все операции с её файлами если для них не указан другой путь. Все относительные пути тоже будут отсчитываться от этой папки.
При запуске терминала текущей папкой считается домашний каталог пользователя. Если программу запускать из определенной папки, то ее текущей папкой будет та папка, из которой ее запустили.
Команда pwd в Linux
Синтаксис команды очень простой:
$ pwd опции
Вот основные опции, которые вы можете использовать для настройки вывода утилиты:
- -L, —logical — брать директорию из переменной окружения, даже если она содержит символические ссылки;
- -P — отбрасывать все символические ссылки;
- —help — отобразить справку по утилите;
- —version — отобразить версию утилиты.
Дальше рассмотрим несколько примеров работы с командой. Для того чтобы просто посмотреть текущую папку Linux достаточно выполнить pwd без параметров:
Также у команды есть одна опция -P. Если по пути к текущей папке есть символические ссылки, то утилита покажет полный путь без учета символических ссылок:
В большинстве командных интерпретаторов pwd — это встроенная команда. Поэтому интерпретатору не нужно вызвать внешнюю утилиту и выполнение когда работает очень быстро.
Чтобы узнать текущую папку в скрипте не обязательно использовать эту команду. Достаточно обратится к переменной окружения PWD:
Но также можно записать результат выполнения команды pwd linux в переменную:
CWD=$(pwd)
echo $CWD
Выводы
Команда pwd Linux используется достаточно редко, намного чаще нам нужно менять текущую папку. Для этого применяется команда cd. Как видите, все очень просто.
Источник