Checking and storing the current working directory in a Linux shell script is commonly accomplished using the built-in pwd command combined with variable assignment. Below are the specific steps and examples:
-
Using the
pwdcommand: Thepwdcommand (an abbreviation for Print Working Directory) displays the full path of the current working directory. -
Storing the output in a variable: You can use command substitution to assign the output of the
pwdcommand to a variable. Command substitution can be achieved using backticksor$(...). -
Verifying the variable content: To ensure the variable correctly stores the directory path, you can use the
echocommand to print the variable's value.
Example script:
bash#!/bin/bash # Get the current working directory current_dir=$(pwd) # Print the current working directory echo "Current working directory is: $current_dir"
In this example, we first create a variable current_dir and assign the output of the pwd command to it using $(pwd). Then, we use the echo command to output the value of this variable, thereby displaying the current working directory.
This method is highly suitable for scenarios where the current working directory needs to be referenced frequently in scripts, as it enhances code readability and maintainability.