Linux/Unix Shell脚本:获取当前目录
时间:2020-01-09 10:43:39 来源:igfitidea点击:
shell脚本如何找出当前的工作目录。
如何获得在Linux或者Unix等操作系统上运行的Bash或者Ksh shell下的当前工作目录?
您可以使用称为PWD的shell程序变量或者内置命令pwd来获取当前的工作目录。
cd命令设置以下shell变量:
OLDPWD由cd命令设置的上一个工作目录。PWD由cd命令设置的当前工作目录。pwd命令打印当前工作目录的名称。
语法
语法为:
echo "The current working directory: $PWD" echo "The previous current working directory: $OPLDPWD" _cwd="$PWD" ## use pwd command ## _mydir="$(pwd)" ## 或者 _mydir="`pwd`" echo "My working dir: $_mydir"
Shell脚本示例
以下脚本使用$PWD两次设置默认值,并向sys管理员提供信息。
#!/bin/bash
# Purpose: Set file permission to read-only
# Author: theitroad <www.theitroad.local> under GPL v2.0+
# --------------------------------------------------------------
# DocumentRoot permissions
_dp="0544"
_fp="0444"
_sp="0744"
# Apache user/group
_user="www-data"
_group="www-data"
## If is not passed, set to the current working dir using $PWD
_dir="${1:-${PWD}}"
## Die if $dir does not exists
[ ! -d "$_dir" ] && { echo "Error: Directory $_dir not found."; exit 2; }
## Get confirmation
echo "I will change file permission for the webserver dir and files to restrictive read-only mode."
read -p "The current working dir is ${PWD}. Are you sure (y / n) ?" ans
## Lowercase $ans and compare it
if [ "${ans,,}" == "y" ]
then
chown -R ${_user}:${_group} "$_dir"
chmod -R $_fp "$_dir"
fi

