我如何将命令输出分配为变量

时间:2014-08-12 12:01:29

标签: bash scripting

嗨,我对脚本非常陌生。如果我指的是错误的话,我很抱歉。

我正在尝试开发一个备份给定路径的脚本。下面是我的脚本。 我面临的问题是我正在尝试分配变量" s"命令" mkdir"它不起作用。请帮帮我,我该如何纠正这种语法?

#!/bin/bash
# to back up the given folder "

i="`date | awk '{ print $1$2$4}'`"
echo " please enter the full path of folder you want to back up"
read foldern

echo " $foldern is of `du -sh $foldern`. Do you want to back up this folder"
echo "yes / no"
read ans

if [ $ans = yes ]
 then
  echo " enter the back up folder name"
  read  bpn
  s=$(mkdir $bpn$i)   # here I am trying to assign a variable "s" for out put of mkdir but dosent work Please help me #
echo $s
 cp -R  "$foldern"  "$s"
 else
   echo "no back up is taken"
fi

1 个答案:

答案 0 :(得分:1)

mkdir不会创建输出或打印它创建的目录。改为手动创建字符串:

s=$bpn$i
mkdir -- "$s"
echo "$s"

--是一个可选的选项 - 参数分隔符,因此以-开头的文件不会被误解为mkdir的错误选项。

如果您不希望-p在目录已存在时显示错误,那么添加mkdir也会有所帮助。

mkdir -p -- "$s"

建议:

#!/bin/bash

# To back up the given folder.

date=$(date | awk '{ print $1$2$4}')  ## Consider date=$(date '+%F-%T')

read -p "Please enter the full path of folder you want to back up: " folder_name

size=$(du -sh "$folder_name")
read -p "$folder_name is of $size. Do you want to back up this folder (Yes/No)? "

if [[ $ans == [yY][eE][sS] ]]; then
    read -p "Enter the back up folder name: " backup_name
    backup_name+=$date
    echo "$backup_name"
    mkdir -p "$backup_name" && cp -R "$folder_name" "$backup_name"
else
    echo "No back up is taken."
fi