'How to create files that should be named like the directories names in Linux?
I want to create files and the names of these files should be like the names of directories in the / directory
I created a shell script like this :
#!/bin/bash
cd /
declare -a array=($(ls -d */));
For i in "${array[@]}"; do
touch $i
done
But it doesn't do anything when I execute it!
Although when I replace the touch with echo, it does print the directories names into the screen.
So I think the problem is with the touch command?
Or if there is another way of doing this instead of shell script?
Solution 1:[1]
I would recommend using find for this:
- Search all dirs
-type d - Limit to 1 folder deep
-maxdepth 1 - Exec a command for each result
-exec sh -c '' - Remove the trailing slash (
/) - Run
touch
find / -type d -maxdepth 1 -exec sh -c 'echo ${0#/} | xargs touch' '{}' \;
Gives the following folder on my MacOs:
$ ls -ltah
total 0
-rw-r--r-- 1 me wheel 0B May 20 11:19 cores
-rw-r--r-- 1 me wheel 0B May 20 11:19 Volumes
-rw-r--r-- 1 me wheel 0B May 20 11:19 dev
-rw-r--r-- 1 me wheel 0B May 20 11:19 opt
-rw-r--r-- 1 me wheel 0B May 20 11:19 Applications
-rw-r--r-- 1 me wheel 0B May 20 11:19 Users
-rw-r--r-- 1 me wheel 0B May 20 11:19 .vol
-rw-r--r-- 1 me wheel 0B May 20 11:19 private
-rw-r--r-- 1 me wheel 0B May 20 11:19 System
-rw-r--r-- 1 me wheel 0B May 20 11:19 Library
-rw-r--r-- 1 me wheel 0B May 20 11:19 sbin
-rw-r--r-- 1 me wheel 0B May 20 11:19 bin
-rw-r--r-- 1 me wheel 0B May 20 11:19 usr
drwxr-xr-x 15 me wheel 480B May 20 11:19 .
drwxrwxrwt 16 root wheel 512B May 20 11:09 ..
$
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0stone0 |
