1

I want to move a series of file into different folder based on their ID, but I want to make sure that the folder I'm moving the file to exists and is unique

The folders have a matching ID as the first part of their name, but also have a description in their name (the ID should be unique, but I want to guard against that exception) :

0123-app1
4567-app2
2020-app3
0123-shouldntbehere

I want to move file with ID 4567 to the directory 4567-app2.

Since the description is in the name, I need to use a wildcard to find the right folder. Right now I tried echoing the name in a variable, but it doesn't help me check if it's unique or if it exists.

APP_PATH=`echo $APP_ID*`

What would suggest I use to find the right folder and validate that it's unique ?

Thanks

1
  • Still not really sure what you are trying to do but you could use this to check for dup folders for i in */;do echo ${i/-*/};done | uniq -d – 123 Aug 4 '15 at 15:11
1

The way I implemented it was with an if statement with an error code check. The [ -d ...] will generate an error if more than one parameter (folder name) are passed when the wildcard is exploded or if the files doesn't exist. The ls in the else allows us to know which case brought us here (if multiple folder exists, the return code will be 0)

if [ -d ${ID}* ] 2>/dev/null; then
    echo "Folder exists and is unique"
else
    ls ${ID}* >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "No folder exists starting with ${ID}"
    else
        echo "More than one folder starting with ${ID}"
    fi
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.