Use wildcards (*) in shell scripts to delete and move a certain directory

Let me talk about the conclusion first: to use wildcards (*) in shell scripts to delete and move a certain directory, you need to save the spliced ​​path in a variable, and then follow the variable with the rm or mv command. If splicing is performed after the rm or mv command, it will not take effect.

See an example:

#!/bin/bash
TEST_TARGET_PATH="/data/"
TEST_BASE_PATH="/localfolder/a9zu2vjk/vw_live_test/"
CUR_DAY=`date -d "1 days ago" +%Y_%m_%d`
TEST_SOURCE_PATH=$TEST_BASE_PATH$CUR_DAY"_*"
echo $TEST_SOURCE_PATH
echo $TEST_BASE_PATH$CUR_DAY"_*"

#这种方式可以删掉
rm -rf $TEST_SOURCE_PATH
#使用以下的方式删不掉文件
rm -rf $TEST_BASE_PATH$CUR_DAY"_*"

#这种方式生效
mv $TEST_SOURCE_PATH $TEST_TARGET_PATH
#这种报错:mv: cannot stat ‘/localfolder/a9zu2vjk/vw_live_test/2023_08_03_*’: No such file or directory
mv $TEST_BASE_PATH$CUR_DAY"_*" $TEST_TARGET_PATH

operation result:

sh test.sh 
/localfolder/a9zu2vjk/vw_live_test/2023_08_03_00_1 /localfolder/a9zu2vjk/vw_live_test/2023_08_03_00_2
/localfolder/a9zu2vjk/vw_live_test/2023_08_03_*

It can be seen from the printout that if the spliced ​​path is saved in a variable, the printed result is the result of expanding the wildcard (*), so it will take effect for the rm or mv command. If it is spliced ​​after the rm or mv command, the rm and mv commands will not take effect.

 

Guess you like

Origin blog.csdn.net/liuxiao723846/article/details/132094858