#!/bin/bash
# Bash script that will produce a text file that has a list of the files in the present working directory
cd /bin
ls -d
ls -d >>file.txt


#!/bin/bash
#Bash script that will copy all the files in one directory to another directory
ls -d
mkdir /EgorDir
cp*.*ls-d /EgorDir
echo "Done"

Recommended Answers

All 2 Replies

Hello,

For the first script, you do not want to use 'ls -d'. Please see the man page for ls (man ls). The -d flag to ls will list a directory itself, without recursing underneath it. With the -d flag, you actually need to pass the directory, or directories as arguments.

In order to get a listing of the files within a directory, just execute 'ls /directory_name' without any arguments at all. Some you may want to consider though are '-a' which shows hidden files, or '-l' which produces more detailed information for the files.

The redirection for the script, >>, will append data to the bottom of whatever file is specified. Chances are you would rather overwrite anything in the current file, if it exists. You can do this by just using >. So, the first script should look something like this:

#!/bin/bash
cd /bin
ls > /tmp/file.txt

Note, adding "/tmp" (or any directory that is writeable to you) is a good idea. Otherwise, your script will try to write the output file to the /bin directory itself, which you should not have write access to, and will thus fail.

For the second script, cd and ls should not be on the same line. To copy files from one directory to another in shell, you would want to use something like:

#!/bin/bash
cp -R /tmp/directory_1 /tmp/directory_2

The -R means "recursive," i.e. copy everything under that directory (including subdirectories) to the new directory. I hope some of this helps.

Regards,
Tom

Tom,
Thank You so much. As You can see I'm a complete novice to scripting, so Your help is very much appreciated.
Thx,
Egor

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.