关于 echo 当前工作目录的 Bash 脚本问题

关于 echo 当前工作目录的 Bash 脚本问题

我有这个代码:

#!/bin/bash 

#clear screen
clear 

# Ask for name of directory to create
echo "Please enter a directory name"
echo "that you wish to create"
read dir1

# create directory
mkdir $dir1

# change to the newly created directory
cd $dir1

# Tell user where he/she is
echo "This directory is called 'pwd'"


# create some files
touch file1 file2 file3


# put in some content 
echo "This is $dir1/file1" > file1
echo "This is $dir1/file2" > file2
echo "This is $dir1/file3" > file3



# announce file names
echo "The files in $dir1 are: "
ls -hl

# show the contents  of the files
echo "The content of the files are: "
cat file1
cat file2
cat file3


echo "Goodbye"

echo "This directory is called 'pwd'" 的行拒绝按预期提供当前工作目录。请帮我解决这个问题,我目前正在学习 BASH SHELL 脚本

答案1

要获取当前工作目录作为多变的

echo $PWD

(大写),或使用命令

pwd

然后,使用多变的,该行应为:

echo "This directory is called '$PWD'"

输出:

This directory is called /home/jacob

答案2

你必须使用

echo "This directory is called $(pwd)"

你想做的事情叫做命令替换。以前这是使用反引号 ( ) 来完成的` `,但目前推荐的方法是使用$()

你可以找到详细的解释在此 wiki 页面中。

相关内容