在我的 shell 脚本中,我有以下几行:
function tarIt() {
FILE_OWNER=$1
TAR_FILE_NAME=$2
FILE_NAME=$3
su - $FILE_OWNER -c "tar -czf $TAR_FILE_NAME $FILE_NAME 2>&1"
if [ ${?} -ne 0 ]; then
print_error "Failed to create backup.";
exit $E_FAILED_COMPRESS;
fi
}
在调试时,我得到以下几行:
+ su - ssrun -c 'tar -cvzf /tmp/backup/statusService/probe.properties.tar.gz /opt/mgtservices/probes/conf/probe.properties 2>&1'
Password: ssrun1
su: incorrect password
+ '[' 125 -ne 0 ']'
+ print_error 'Failed to create backup.'
我不知道在提示输入密码时,为什么我的文本可见并且密码也没有被获取。密码是正确的,当我在命令提示符下复制同一行时,它执行时没有任何错误。
以下是上传的脚本。这有我从另一个脚本调用的实用方法。
#!/bin/bash
# Exit Status
E_DIR_NOT_EXIST=55; # error if directory does not exist
E_DIR_PERMISSION_DENIED=77; # error if directory does not exist
if [ -z "${V9UPGRADE_LOG}" ]
then
LOGFILE=/tmp/${SCRIPTNAME}.$(date +'%Y%m%d_%H%M%S').log;
else
LOGFILE=${V9UPGRADE_LOG};
fi
# Verifies the run user or root user
if ! [[ $(whoami) =~ ^(ssrun|root)$ ]]
then
print_error "You have to be user ssrun or root to perform this operation.";
exit ${E_USER};
fi
# Function to log information
function print_info() {
format="$1"
shift
printf "$(date +'%F %T') ${SCRIPTNAME}: INFO: $format\n" "$@" | tee -a ${LOGFILE};
}
# Function to log warning
function print_warn() {
format="$1"
shift
printf "$(date +'%F %T') ${SCRIPTNAME}: WARN: $format\n" "$@" | tee -a ${LOGFILE};
}
# Function to log error
function print_error() {
format="$1"
shift
printf "$(date +'%F %T') ${SCRIPTNAME}: ERROR: $format\n" "$@" | tee -a ${LOGFILE} >&2;
}
function validateDir4Permission() {
DIR=$1
[ -d $DIR ] || { print_error "Invalid directory $DIR"; exit $E_DIR_NOT_EXIST; }
( su - $RUNUSR -c "[[ -rwx $DIR ]]" ) || { print_error "$DIR has insufficient permissions for ssrun user"; exit $E_DIR_PERMISSION_DENIED; }
( su - $ESYUSR -c "[[ -rwx $DIR ]]" ) || { print_error "$DIR has insufficient permissions for ne3suser user"; exit $E_DIR_PERMISSION_DENIED; }
[[ -rwx $DIR ]] || { print_error "$DIR has insufficient permissions for current user"; exit $E_DIR_PERMISSION_DENIED; }
}
# Function to append ".tar.gz" to name of file
function getArchiveFileName() {
echo ${SS_BACKUP_DIR}/${1}.tar.gz
}
# Function to compress the files and store in backup directory.
function tarIt() {
FILE_NAME=$1
TAR_FILE_NAME=$(getArchiveFileName $2)
FILE_OWNER=$3
if [[ -f $TAR_FILE_NAME ]]; then
print_info "$TAR_FILE_NAME already exists. Removing current instance.";
rm -f $TAR_FILE_NAME;
fi
su - $FILE_OWNER -c "tar -zcf $TAR_FILE_NAME $FILE_NAME > 2>&1"
if [ $? -ne 0 ]; then
print_error "Failed to compress $TAR_FILE_NAME."
exit $E_FAILED_COMPRESS;
else
if [[ -f $FILE_NAME ]]; then
print_info "File %s is backed up at %s" "$FILE_NAME" "$SS_BACKUP_DIR"
else
print_info "$All the contents of directory %s are compressed to %s." "$FILE_NAME" "$TAR_FILE_NAME"
fi
fi
}