This repository contains solutions to various command-line tasks from the CMD Challenge. Each challenge is designed to test and improve your shell scripting and command-line skills. Below is the list of challenges and their solutions, along with detailed explanations to help beginners understand the concepts.
Task: Print "hello world".
Solution:
echo "hello world"Explanation:
echois a command used to display text or strings on the terminal.- By typing
echo "hello world", the shell will output the texthello worldto the screen.
Task: Print the current working directory.
Solution:
pwdExplanation:
pwdstands for "print working directory."- This command displays the full path of the directory you are currently in.
Task: List all of the files in the current directory, one file per line.
Solution:
ls -1Explanation:
lslists files and directories in the current directory.- The
-1option ensures that each file is displayed on a separate line.
Task: Print the last 5 lines of access.log.
Solution:
tail -5 access.logExplanation:
taildisplays the last part of a file.- The
-5option tellstailto show the last 5 lines of the fileaccess.log.
Task: Print all lines in access.log that contain the string "GET".
Solution:
grep GET access.logExplanation:
grepsearches for a specific pattern in a file.- Here, it searches for the word
GETin the fileaccess.logand prints all matching lines.
Task: Print all files, one per line, that contain the string "500".
Solution:
grep -rl * -e 500Explanation:
grepsearches files for a given pattern.-rmeans recursive, so it searches in the current directory and all subdirectories.-lmeans it only prints the names of files containing the match, not the matching lines.*searches all files in the current directory.-e 500specifies the string500to search for.
Task: Print the relative file paths for all files that start with access.log.
Solution:
find . -name "access.log*"Explanation:
findsearches for files and directories..specifies the current directory.-nametellsfindto look for files matching a specific name pattern."access.log*"matches any file name starting withaccess.log.
Task: Print all matching lines (without the filename or file path) in files starting with access.log and containing the string "500".
Solution:
find . -name "access.log*" | xargs grep -h 500Explanation:
find . -name "access.log*"finds all files starting withaccess.log.- The
|symbol pipes the output offindinto the next command. xargspasses the file names togrep.grep -hsearches for500but hides file names from the output.
Task: Extract all IP addresses from files that start with access.log, printing one per line.
Solution:
find . -name "access.log*" | xargs grep -Eo '^[^ ]+'Explanation:
find . -name "access.log*"finds files starting withaccess.log.xargspasses the file names togrep.grep -Eo '^[^ ]+'extracts patterns using regular expressions:-Eenables extended regular expressions.-oprints only the matching part of the line.'^[^ ]+'matches the beginning of a line until the first space, which is often the IP address in logs.
Task: Delete all files in the current directory, including subdirectories and their contents.
Solution:
find . -deleteExplanation:
find .searches in the current directory and all subdirectories.-deleteremoves the files and directories found byfind. Note: Be very careful when using this command as it will delete everything in the specified directory!
Task: Count the number of files in the current working directory.
Solution:
ls | wc -lExplanation:
lslists files in the current directory.- The
|passes the output oflstowc(word count). wc -lcounts the number of lines, which equals the number of files.
Task: Print the contents of access.log sorted.
Solution:
sort access.logExplanation:
sortarranges the lines of a file in alphabetical or numerical order by default.- Here, it sorts the lines in
access.log.
Task: Print the number of lines in access.log containing the string "GET".
Solution:
grep GET access.log | wc -lExplanation:
grep GET access.logfinds all lines containingGET.- The
|passes these lines towc -l. wc -lcounts the number of matching lines.
Task: Split the numbers in split-me.txt on the ; character, printing one per line.
Solution:
cat split-me.txt | sed 's/;/
/g'Explanation:
cat split-me.txtoutputs the content of the filesplit-me.txt.|pipes the output tosed.sed 's/;/ /g'replaces each semicolon (;) with a newline character (), printing each number on a new line.
Task: Print the numbers 1 to 100 separated by spaces.
Solution:
echo {1..100}Explanation:
echooutputs text to the terminal.{1..100}is a sequence expression that generates numbers from 1 to 100.- This prints all numbers in a single line, separated by spaces.
Task: Remove all .doc files recursively in the current directory.
Solution:
find . -name "*.doc" -deleteExplanation:
find . -name "*.doc"searches for files ending with.doc.-deleteremoves these files.
Task: Delete "challenges are difficult" from all .txt files.
Solution:
find . -name "*.txt" -exec sed -i 's/challenges are difficult//g' {} +Explanation:
find . -name "*.txt"locates all.txtfiles.-execruns a command on each file found.sed -i 's/challenges are difficult//g'removes the text "challenges are difficult" from each file in place (-i).
Task: Print the sum of numbers in sum-me.txt.
Solution:
cat sum-me.txt | xargs | sed 's/ /+/g' | bcExplanation:
cat sum-me.txtoutputs the file's content.xargsjoins all numbers into a single line.sed 's/ /+/g'replaces spaces between numbers with+signs to form a mathematical expression.bcevaluates the expression and prints the result.
Task: Print all files in the current directory recursively without leading paths.
Solution:
find . -type f -printf "%f\n"Explanation:
find .searches the current directory and subdirectories.-type frestricts the search to files (not directories).-printf "%f\n"prints only the filenames without their paths.
Task: Remove file extensions recursively.
Solution:
find . -type f -exec bash -c 'mv "$1" "${1%.*}"' - '{}' \;Explanation:
find . -type ffinds all files in the current directory and subdirectories.-exec bash -cruns a custom bash command for each file.mv "$1" "${1%.*}"renames the file by removing everything after the last.(dot), which is the file extension.
Task: Replace spaces in filenames with a . character.
Solution:
find . -type f -name "* *" | while read -r file; do mv "$file" "${file// /_}"; doneExplanation:
find . -type f -name "* *"finds files with spaces in their names.- The
|pipes the list of filenames to awhileloop. mv "$file" "${file// /_}"renames each file by replacing spaces with underscores (_).
Task: Print filenames starting with a number.
Solution:
find . -name '[0-9]*' -type f -printf "%f\n"Explanation:
find . -name '[0-9]*'searches for files whose names start with a digit.-type fensures only files are included.-printf "%f\n"prints only the filenames.
Task: Print the 25th line of faces.txt.
Solution:
sed '25q;d' faces.txtExplanation:
sedis used to process and transform text in a file.'25q;d'tellssedto quit (q) after reading 25 lines, and delete (d) all but the 25th line.
Task: Print faces.txt with only the first instance of each duplicate line.
Solution:
awk '!seen[$0]++' faces.txtExplanation:
awkprocesses text line by line.!seen[$0]++ensures each line is printed only the first time it is encountered.
Task: Remove random ! marks from war_and_peace.txt to restore the original text.
Solution:
< war_and_peace.txt tr -s '!' | sed 's/!//g'Explanation:
tr -s '!'squeezes multiple!into a single one.sed 's/!//g'removes all remaining!characters.
Task: Print "Hello World" using escaped space.
Solution:
echo hello\ worldExplanation:
hello\ worldescapes the space with a\, ensuring the two words are treated as part of the same string.
Task: Count lines containing tab characters in file-with-tabs.txt.
Solution:
grep -c $'\t' file-with-tabs.txtExplanation:
grep -ccounts the number of matching lines.$'\t'matches tab characters.
Task: Remove files starting with a dash in the filename.
Solution:
find . -name '-*' -deleteExplanation:
find . -name '-*'searches for files starting with a dash (-).-deleteremoves those files.
Task: Remove all files without .txt and .exe extensions recursively.
Solution:
find . -type f -not \( -name '*.txt' -or -name '*.exe' \) -deleteExplanation:
find . -type ffinds all files.-not \( -name '*.txt' -or -name '*.exe' \)excludes.txtand.exefiles.-deleteremoves all other files.
Task: Print IP addresses common to access.log.1 and access.log.2.
Solution:
comm -12 <(cut -d' ' -f1 access.log.1 | sort) <(cut -d' ' -f1 access.log.2 | sort)Explanation:
cut -d' ' -f1extracts the first column (IP addresses) from each file.sortarranges the IPs in order.comm -12finds common lines between the two sorted files.
Task: Print the lines of the file reverse-me.txt in reverse order so that the last line appears first.
Solution:
tac reverse-me.txtExplanation:
tacprints a file line by line in reverse order.
Task: Print the number of unique prime numbers in random-numbers.txt.
Solution:
cat random-numbers.txt | sort | uniq | factor | awk 'NF==2' | wc -lExplanation:
sort | uniqeliminates duplicate numbers.factorbreaks numbers into their prime factors.awk 'NF==2'filters lines with exactly two fields (prime numbers only).wc -lcounts the number of unique primes.
Task: Print all IPv4 listening ports from netstat.out, sorted in descending order.
Solution:
grep '\bLISTEN\b' netstat.out | grep -oP 'tcp\s+.*:\K\d+' | sort -nrExplanation:
grep '\bLISTEN\b'filters lines containingLISTEN.grep -oP 'tcp\s+.*:\K\d+'extracts port numbers using Perl-compatible regular expressions.sort -nrsorts the port numbers in descending numerical order.
Task: Watch for any changes in the logs directory and display them in real-time.
Solution:
inotifywait -m logsExplanation:
inotifywaitis a tool for monitoring file system events.-menables monitoring mode to keep the command running.logsspecifies the directory to monitor. It displays events like file modifications, deletions, and creations.
Task: Count the number of failed SSH login attempts in /var/log/auth.log.
Solution:
grep "Failed password" /var/log/auth.log | wc -lExplanation:
grep "Failed password"searches for failed login attempts in the log file.wc -lcounts the number of matching lines.
Task: Display all open network connections and their statuses.
Solution:
netstat -tulnExplanation:
netstatdisplays network statistics.-tulnshows TCP/UDP connections (t/u), listening ports (l), and numeric addresses (n).
Task: Find all files with the SUID bit set on the system.
Solution:
find / -perm -4000 2>/dev/nullExplanation:
find /searches the entire filesystem.-perm -4000matches files with the SUID bit set.2>/dev/nullsuppresses permission-denied errors.
Task: Find the top 5 largest directories in the /var directory.
Solution:
du -h /var | sort -rh | head -n 5Explanation:
du -h /varcalculates the size of each directory in human-readable format.sort -rhsorts by size in reverse order.head -n 5displays the top 5 results.
Task: List all currently logged-in users.
Solution:
whoExplanation:
whodisplays information about users currently logged into the system.
Task: List all open files by the nginx process.
Solution:
lsof -c nginxExplanation:
lsoflists open files.-c nginxfilters for files opened by processes namednginx.
Task: Generate a SHA256 checksum for the file backup.tar.gz.
Solution:
sha256sum backup.tar.gzExplanation:
sha256sumcalculates the SHA256 hash of a file to verify its integrity.
Task: Permanently delete sensitive.txt without recovery.
Solution:
shred -u sensitive.txtExplanation:
shredoverwrites the file multiple times before deleting it.-uensures the file is deleted after shredding.
Task: Display real-time memory usage.
Solution:
watch -n 1 free -hExplanation:
watch -n 1runs a command every second.free -hdisplays memory usage in human-readable format.
Task: Identify processes using high CPU usage.
Solution:
ps aux --sort=-%cpu | head -n 10Explanation:
ps auxlists all running processes.--sort=-%cpusorts them by CPU usage in descending order.head -n 10shows the top 10 results.
Task: Extract the subdomain from a list of URLs in websites.txt.
Solution:
awk -F[/:] '{print $4}' websites.txtExplanation:
awkprocesses text line by line.-F[/:]uses/and:as field separators.{print $4}extracts the fourth field, which is the subdomain or domain.
Task: Find files modified in the last 24 hours.
Solution:
find . -type f -mtime -1Explanation:
find . -type flocates all files.-mtime -1matches files modified within the last day.
Task: Display all open ports on the system.
Solution:
ss -tulnExplanation:
ssdisplays socket statistics.-tulnshows TCP/UDP connections, listening ports, and numeric addresses.
Task: Terminate all processes named apache2.
Solution:
pkill apache2Explanation:
pkillsends signals to processes by name.apache2is the name of the processes to terminate.
49. Detect Hidden Files π
Task: Find all hidden files in the current directory.
Solution:
find . -type f -name ".*"Explanation:
find . -type flocates all files.-name ".*"matches hidden files (names starting with.).
Task: Display how long the system has been running.
Solution:
uptimeExplanation:
uptimeshows the current time, uptime duration, and load averages.