Write a Bash shell script program which creates 3 directories dir1, dir2, dir3 and then places the following files into each directory file1, file2. file1 is a zero size and file2 has the current date/time as the contents. Create a file named file3 that is only put into the dir3 directory that contains the line from the /etc/hosts file that contains your hostname. Use a loop to create the directory and files. You will need to use an if condition block to create file3 with the commands grep and hostname.

closed as unclear what you're asking by Jeff Schaller, roaima, Stephen Rauch, Scott, Anthon Sep 13 '17 at 6:12

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • I been using this for reference but i'm obviously missing something if [ $# -lt 3 ] then echo "Usage: $0 filename filename filename" echo "Example: $0 Mary f1 f2 f3" echo "Comments: Create a directory (e.g., Mary) and fill it with the named files (e.g., f1 f2 f3)" exit 1 fi #The next line makes the directory mkdir $1 #The next line cds into that directory cd $1 #The following line uses the "touch" command to make 3 files. touch $2 $3 $4 for i in * do cp $i .. done – Joshua Apr 20 '16 at 8:48
  • 3
    You can edit your post with more information. You will get a better response if you show some level of effort. – Michael Homer Apr 20 '16 at 8:49
  • 2
    nobody's going to put in the effort to read a comment like that. Edit your question and add it there. Use the {} icon to format it as code. – cas Apr 20 '16 at 9:17

There is no need for any looping. In fact, that would only be confusing an inefficient.

mkdir dir{1..3}
touch dir{1..3}/file1
date | tee dir{1..3}/file2 >/dev/null
grep "$(hostname)" /etc/hosts >dir3/file3

The only slightly advanced thing with this answer is the use of tee. The tee utility will take data on standard input and duplicate this to a number of files, and again to standard output. I use it here to write the date from the date utility into the three file2 files. The redirection to /dev/null at the end is there so that we don't also get the date displayed in the terminal.

In the code above, dir{1..3} would be expanded to dir1 dir2 dir3 and dir{1..3}/file1 would be expanded to dir1/file1 dir2/file1 dir3/file1 before the utility is invoked with that as its arguments.


This will do :

for i in {1..3}; do 
  mkdir dir$i
  touch dir$i/file1 
  date > dir$i/file2 
  if [ $i -eq 3 ]; then 
    grep $(hostname) /etc/hosts > dir$i/file3

Not the answer you're looking for? Browse other questions tagged or ask your own question.