-1

I was trying to create a script that monitors the /media/user directory. When a new USB is plugged in the script would run and add the new directory to a program that now uses the new USB drive.

For example:

for D in ls -l /media/user
do
    directory add -d D
done

currently that script just literally adds /media/user/D as many times as there are directories in /media/user not the specific directory names in /media/user/D

The command directory add -d adds the directory and I want it to add /media/user/drive1, /media/user/drive2 etc

Thanks I'm obviously new!

Ljm Dullaart
  • 4,643

2 Answers2

1

This is very basic bash stuff. Let's go through your script.

for D in ls /l /media/user
do

You create a for-loop with the variable D which loops over

  • ls
  • /l
  • /media/user

so, it will execute 3 times.

    directory add -d D

I don't know what the program directory is supposed to do; I don't know it. However, it is executed 3 times exactly the same way, with the same arguments:

  • add
  • -d
  • D
done

The end of your for-loop.

That is not exactly the behavior that you describe; it will add always exactly 3 times litterally D.

Now for the improvements.

You do not want to run exactly 3 times, but you want to run for every directory in /media/user. So, an obvious choice would be to use $(ls -l /media/user). Now, I do not know what kind of format your directory program expects as argument, but if it isn't

-rw-r--r-- 1 ljm users   27164672 Jun 19 00:30 mikrotik-6.47.10.iso

then you probably do not want the -l option. Also, parsing the output of ls is in general a bad idea. So, what you're probably looking for is

for D in /media/user/* 
do

Next id your directory program. It is always called with D as last argument. Not the value of D, that would be $D. That means that you probably want to

directory add -d $D

But, if the directory name has a space in it, this will split the directory name into two arguments. So quoting is required:

directory add -d "$D"

Hope that gets you a bit better on track.

Ljm Dullaart
  • 4,643
  • Thanks for the breakdown. It is very simple and I'm just learning. I appreciate the very descriptive steps. I got it to work. I think I was confusing everyone by using 'directory' as my program, which it is not. I should have chosen the generic 'program' in hindsight. – davefromcamp Jun 19 '21 at 21:04
  • is there a way to have the script trigger when a new usb drive is attached? monitor the folder or as a suggestion above – davefromcamp Jun 19 '21 at 21:25
0
  1. Don't use ls in a script.

  2. There is no "directory" command; mkdir creates directories, though. You can read its 'man' page.

So try replacing that first line as for D in /media/user/*

Jeremy Boden
  • 1,320
  • He is not using $(ls -l ...); he is using literally ls. There's no rule against that. directory is his apparently his own program. – Ljm Dullaart Jun 19 '21 at 16:28