简体   繁体   中英

Linux mkdir, find and mv

So guys, I have to write this script in Linux. I have to create a directory and see if it already exists or not and then I have to find all the file which end in ".c" and move them to the directory I created. This is what I have so far:

#!/bin/bash

while

    echo "name of the directory you want to create " 

    read -p "$name"; do

    if [ ! -d "$name" ]; then

    {
        echo "Directory doesn't exist. Create: "

        read -p "$name"

        mkdir -p Scripts/"$name" 

    }

    else

        echo "Directory exists"

    fi

    find ./ -name '*.c' | xargs mv -t "$name"

done

When I try to execute it, it doesn't work. It doesn't create a new directory and also it says:

mv: failed to access '': No such file or directory.

Can you please help me find a solution to this?

I'm not exactly sure what you're trying to achieve. But there are a few things in your script that don't make sense.

  1. What do you need a while loop for? Once you've made the folder and moved all scripts, there's no sense in running it again.
  2. Why do you read the name of the directory twice? You can just read it once, store it in $name and use it until the end of the script.
  3. You don't need find *.c will select all files ending with .c in the current directory.

With all that said, here's the script that does what you requested if I understood correctly.

#! /bin/bash
echo -n "Enter the name of the directory you want to create: "
read name

if [ ! -d Scripts/"$name" ]; then
    echo "Directory doesn't exist. Creating it."
    mkdir -p Scripts/"$name"
else
    echo "Directory exists"
fi

echo "Moving files"
mv *.c Scripts/"$name"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM