I was wondering how this looks. I am trying to create a script that will produce a text file that has a list of the files in the present working directory. How do you go about testing this script?

#!/bin/bash
#
# Matthew Smith# Comp230
ls >FILE.txt

Dani AI

Generated

Good start — this is exactly the sort of small shell task that teaches a lot about quoting, globs and testing. As started, you are writing a shell script; covered running and permissions, and reminded you to include the interpreter line at the top. Two quick, safe testing options are to invoke the interpreter explicitly or run the file after making it executable.

To test and debug, run the script under the shell (for example with bash scriptname) and enable tracing to see each command as it runs (set -x or bash -x). Make the script fail fast in real tests with set -euo pipefail so mistakes stop early; the Bash manual documents these options The Set Builtin.

The copy command in the later post needs a couple of fixes: create the destination first, preserve attributes, and include hidden files. A reliable pattern is to make the target directory and copy the entire source tree (dotfiles included) or use rsync for a robust mirror. Example workflows:

mkdir -p newdir
cp -a "dir/." "newdir/"

# or, for safer/more informative syncs
rsync -a --progress --dry-run dir/ newdir/

cp -a preserves metadata; dir/. includes files beginning with a dot (globs like dir/* do not). For large or ongoing copies, prefer rsync (see the rsync man page) because it supports dry-runs, partial transfers and checksums rsync man page.

Quick troubleshooting checklist: test on a small sample directory first, use absolute paths to avoid surprises, always quote variables that may contain spaces, and consider a dry-run before destructive operations. For details on cp and mkdir behavior, refer to the GNU coreutils docs cp invocation and mkdir invocation.

Recommended Answers

All 4 Replies

Save the file with a .sh extension, then add executable permissions:

$ chmod ugo+x shell-script.sh

Now run it:

$ ./shell-script.sh

Note that your current directory doesn't have to be where the script is to run it:

$ /some/path/shell-script.sh

I am a little confused as what program you need to run this code?

Also I need some help here with this code. I need to create a bash script that will copy all the files and subdirectories in one directory to a newly created directory. Here's what I came up with.

cp -R dir/*newdir/*

You pretty much have your entire script right there, assuming you don't need to be any more creative, just add a

#!/bin/bash

line to the top and make it executable, etc, per the above post by John A

Best wishes,

Mike

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.