bash unix shell 脚本 - 在 if 条件下使用 mv 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26100049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:25:56  来源:igfitidea点击:

unix shell scripting- Using mv command in if condition

bashunix

提问by Swanand

I want to move a file to a folder based on its file extension. example: if the file is .csv,it should move to COMPLETED folder , if the file has any extension other any .csv then it should move to REGULAR folder.

我想根据文件扩展名将文件移动到文件夹。例如:如果文件是 .csv,它应该移动到 COMPLETED 文件夹,如果文件有任何其他扩展名 .csv 那么它应该移动到 REGULAR 文件夹。

Below is my shell script and its not working. Can you let me know what is the problem with it?

下面是我的 shell 脚本,它不起作用。你能告诉我它有什么问题吗?

#!/bin/bash
cd /apps/int/apd//work

if ls /apps/int/apd//work/*.csv &> /dev/null; then
    mv *.csv /apps/int/apd//COMPLETED
else
    /apps/int/apd//Regular
fi

回答by Fazlin

Why do you have to check the existence of *.csvfiles?

为什么要检查*.csv文件是否存在?

#!/bin/bash
cd /apps/int/apd//work

mv *.csv /apps/int/apd//COMPLETED 2>/dev/null
mv * /apps/int/apd//Regular

Here first .csvfiles are moved to COMPLETEDfolder. Then rest of the files are moved to Regularfolder.

这里第一个.csv文件被移动到COMPLETED文件夹。然后其余的文件被移动到Regular文件夹中。

I am assuming you have created COMPLETEDand Regularfolders.

我假设你已经创建COMPLETEDRegular文件夹。

回答by adimoise91

Change YOUR_PATH with your specific path and your path for /COMPLETED/ and /REGULAR/.

使用您的特定路径以及 /COMPLETED/ 和 /REGULAR/ 的路径更改 YOUR_PATH。

If I got what you wanted to explain i think your variables look like theese:

如果我得到了您想要解释的内容,我认为您的变量看起来像这些:

/YOUR_PATH/ = /apps/int/apd//work
/COMPLETED/ = /apps/int/apd//COMPLETED
/REGULAR/ = /apps/int/apd//Regular    

You can try this. :)

你可以试试这个。:)

#!/bin/bash

for filename in /YOUR_PATH/*;
do
    Path="$filename"
    extension="${filename##*.}"
    if [ "${extension}" = 'csv' ]; then
            mv $Path /COMPLETED/
    else
            mv $Path /REGULAR/
    fi
done

If you need anything pls leave a comment. :)

如果您需要任何东西,请发表评论。:)