Skip to content

Commit 3cb1e27

Browse files
committed
implementing shell tools exercise is compleat
1 parent 4350f48 commit 3cb1e27

3 files changed

Lines changed: 121 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/bin/bash
2+
3+
set -euo pipefail
4+
5+
number_lines=false
6+
number_non_empty=false
7+
8+
# check for flags
9+
if [ "${1:-}" = "-n" ]; then
10+
number_lines=true
11+
shift
12+
elif [ "${1:-}" = "-b" ]; then
13+
number_non_empty=true
14+
shift
15+
fi
16+
17+
count=1
18+
19+
# Loop through all files
20+
21+
for file in "$@"
22+
do
23+
while IFS= read -r line
24+
do
25+
if [ "$number_lines" = true ]; then
26+
echo "$count $line"
27+
count=$((count+1))
28+
29+
else if [ "$number_non_empty" = true ]; then
30+
if [ -n "$line" ]; then
31+
echo "$count $line"
32+
count=$((count+1))
33+
else
34+
echo ""
35+
fi
36+
37+
else
38+
echo "$line"
39+
fi
40+
fi
41+
done < "$file"
42+
done

implement-shell-tools/ls/my-ls.sh

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/bin/bash
2+
set -euo pipefail
3+
4+
show_all=false
5+
6+
# handle -a
7+
if [ "${1:-}" = "-a" ]; then
8+
show_all=true
9+
shift
10+
fi
11+
12+
# directory (default current)
13+
dir="."
14+
15+
if [ "${1:-}" != "" ]; then
16+
dir="$1"
17+
fi
18+
19+
#choose pattern
20+
if [ "$show_all" = true ]; then
21+
files="$dir"/.*
22+
else
23+
files="$dir"/*
24+
fi
25+
# loop
26+
for file in $files
27+
do
28+
name="$(basename "$file")"
29+
30+
if [ "$name" = "." ] || [ "$name" = ".." ]; then
31+
continue
32+
fi
33+
echo "$name"
34+
done

implement-shell-tools/wc/my-wc.sh

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/bin/bash
2+
3+
set -euo pipefail
4+
5+
flag="all"
6+
7+
if [ "${1:-}" = "-l" ]; then
8+
flag="l"
9+
shift
10+
elif [ "${1:-}" = "-w" ]; then
11+
flag="w"
12+
shift
13+
elif [ "${1:-}" = "-c" ]; then
14+
flag="c"
15+
shift
16+
fi
17+
18+
for file in "$@"
19+
do
20+
if [ -d "$file" ]; then
21+
continue
22+
fi
23+
24+
lines=0
25+
words=0
26+
chars=0
27+
28+
while IFS= read -r line
29+
do
30+
lines=$((lines + 1))
31+
words=$((words + $(echo "$line" | wc -w)))
32+
chars=$((chars + ${#line} + 1))
33+
done <"$file"
34+
35+
if [ "$flag" = "l" ]; then
36+
echo "$lines $file"
37+
elif [ "$flag" = "w" ]; then
38+
echo "$words $file"
39+
elif [ "$flag" = "c" ]; then
40+
echo "$chars $file"
41+
else
42+
echo "$lines $words $chars $file"
43+
fi
44+
done
45+

0 commit comments

Comments
 (0)