Search code examples
linuxfindmkdirmv

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?


Solution

  • 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"