0

I got a folder /srv/log/ on a Linux server where I have subfolders with the server names:

server1 server2 server3 server4

I need a command which will show me what is inside of those folders, but only specific ones which i have in text file "del_list":

server2 
server4

I am trying to use a loop:

for i in `cat del_list`; do `ls /srv/log/$i/`; done

but it shows me only part of those servers and error:

-bash: folder1: command not found
-bash: folder2: command not found

but there are many other folders:'folder2, folder3' there. But I cannot list them using my command, what did I do wrong here?

tripleee
  • 175,061
  • 34
  • 275
  • 318
joker20
  • 53
  • 2
  • 8

5 Answers5

1
for i in `cat del_list`; do ls /srv/log/$i/; done

without the backtick around the command after the do

Marco Caberletti
  • 1,353
  • 1
  • 10
  • 13
1

If you can run a python scrpit:

#! /usr/bin/python3
import subprocess
import os

with open("del_list", "r") as f:
    data = f.read().split(" ")
    
    for file in data:
        filepath = "/srv/log/" + file
        if os.path.isdir(filepath):
            subprocess.check_call("ls " + filepath, shell=True)
        else:
            print("Path " + filepath + " not exist!")
1

With a recent bash:

mapfile -t < del_list
ls "${MAPFILE[@]/#//srv/logs/}"
Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51
0

am trying to use a loop: for i in cat del_list; do ls /srv/log/$i/; done

Don't read lines with for

With find and grep

find /srv/logs -type d | grep -Ff del_list

Now to save the output in an array using mapfile which is a bash4+ feature.

mapfile -t array < <(find /srv/logs -type d | grep -Ff del_list)

Now you can use ls for interactive use.

ls "${array[@]}"
Jetchisel
  • 7,493
  • 2
  • 19
  • 18
0

If you need to do something with the matches and not just print them, probably loop over them:

while IFS= read -r folder; do
    for file in "$folder"/*; do
        : something with "$file"
    done
done <del_list

To just run a single command, you can avoid the inner loop:

while IFS= read -r folder; do
   ls "$folder"/*
done <del_list

(though generally don't use ls in scripts.)

This is portable to Bourne sh / POSIX shell, and a very basic shell programming idiom.

The IFS= is useful to prevent the shell from breaking up significant whitespace. The -r option to read is useful to disable the peculiar processing of backslashes which was implemented in the read command in the original Bourne shell, and kept in POSIX for reasons of backwards compatibility. And, as always, you want to quote variables unless you specifically require the shell to perform word splitting and wildcard expansion on the values.

tripleee
  • 175,061
  • 34
  • 275
  • 318