bash
  • case-statement
  • 2016-01-05 42 views 0 likes 
    0

    我现在已经叫了几个文件FILE1.TXT FILE2.TXT file3.txt使用bash case语句来删除文件

    我想创建一个case语句来选择要删除和我目前有:

    files=" " 
    read number 
    
    case $number in 
    1) files=rm file1.txt ;; 
    2) files=rm file2.txt ;; 
    3) files=rm file3.txt ;; 
    *) files='this file does not exist' ;; 
    esac 
    echo $options 
    

    但是,每当我尝试运行它时,它都会显示一个错误,如“file1.txt:command not found”。

    任何人都可以解释我在做什么错吗?

    +0

    顺便说一句,使用名为'files'的标量变量来存储(大概)一个*列表*文件是坏的。标量本质上只能存储一个值;如果您依赖于能够将空间上的值分割以获取文件名列表,那么在尝试使用名称中包含空格的文件时会感到非常失望。 –

    +0

    ......作为读者,我不清楚为什么你的脚本中有一个'files'变量。为什么不直接运行删除? –

    +0

    我把这个标记为重复的问题不是*完全* on-point本身,而是接受的答案直接解决了这个问题。 –

    回答

    0
    files=rm file1.txt 
    

    ...运行file1.txt与环境变量files设置为值rm的命令。

    这通常是任何简单命令前面有KEY=VALUE对这些对被视为环境变量,仅在该命令的持续时间内设置。


    也许你不是想:

    files=file1.txt 
    

    ...或:

    files=() # create an empty array, not a scalar (string) variable. 
    read number 
    case $number in 
        1) files+=(file1.txt) ;; # or simply: 1) rm file1.txt ;; 
        2) files+=(file2.txt) ;; # or simply: 2) rm file2.txt ;; 
        3) files+=(file3.txt) ;; # or simply: 3) rm file3.txt ;; 
        *) echo "This file does not exist" >&2 ; exit 1;; 
    esac 
    
    # ...if collecting filenames in an array, then... 
    echo "Removing files:" >&2 
    printf ' %q\n' "${files[@]}" >&2  # ...expand that array like so. 
    
    rm -f "${files[@]}" # likewise 
    

    要理解为什么像cmd='rm file1.txt'将是 - 而正确的语法 - 很不好的做法,并开放自己的错误,见BashFAQ #50

    +0

    你的选择只是把它作为1)rm file1。 TXT等,完美的作品,非常感谢你! –

    相关问题