乐闻世界logo
搜索文章和话题

How can you check the current working directory in a Linux shell script and store it in a variable?

1个答案

1

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:

  1. Using the pwd command: The pwd command (an abbreviation for Print Working Directory) displays the full path of the current working directory.

  2. Storing the output in a variable: You can use command substitution to assign the output of the pwd command to a variable. Command substitution can be achieved using backticks or $(...).

  3. Verifying the variable content: To ensure the variable correctly stores the directory path, you can use the echo command 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.

2024年8月14日 13:01 回复

你的答案