Skip to content

Instantly share code, notes, and snippets.

@ynonp
Last active August 15, 2017 13:27
Show Gist options
  • Save ynonp/8542719 to your computer and use it in GitHub Desktop.
Save ynonp/8542719 to your computer and use it in GitHub Desktop.

Unix Scripting Lab - Solutions

Part 1: Welcome to Unix

  1. Login to your Unix account
  2. Find your current shell, the default shell and a list of all installed shells.
  • current shell: echo $0
  • default shell: echo $SHELL
  • all shells: cat /etc/shells
  1. List all files and directories in /etc folder ordered by size (hint: man ls).
  • ls -lS /etc/
  1. Print the current date and time formatted as follows:
    Sun 21/03/2010, 14:30 (hint: man date)
  • date +'%a %d/%m/%Y, %H:%M'

Part 2: Files and directories

  1. Create a new directory for the course in your home folder called lab. Inside, create the following files:
    • main.c, game.c, enemy.c, hero.c, a.out
    • monster.h, human.h
    • .highscore
mkdir lab
cd lab
touch main.c game.c enemy.c hero.c a.out monster.h human.h .highscore
  1. Create the following directories under lab
    • Music, Misc, Drivers
mkdir Music Misc Drivers
  1. Place copies of /etc/passwd in all 3 directories (Music, Misc and Drivers)
cp /etc/passwd Music
cp /etc/passwd Misc
cp /etc/passwd Drivers
  1. Create a new text file named myinfo in your home directory and write in it your name, your favorite programming language and why you love unix).
  • pico myinfo
  1. Create a new directory named myinfo and move the new file you created into it. Did you get an error ? Can you fix it ?
mkdir myinfo.d
mv myinfo myinfo.d
mv myinfo.d myinfo
  1. In the file main.c write a small c program that prints "Hello World" on screen. Compile it with gcc and run the result.
gcc main.c
./a.out
  1. Move all .c files to Music folder
mv main.c game.c enemy.c hero.c Music
  1. Move the folder Music with all its contents to Drivers folder
mv Music Drivers
  1. The program ifconfig displays information about the server's network configuraiton. Find out where it is installed and run it. What is your server's IP address ?
locate ifconfig
/sbin/ifconfig
  1. Try to run rmdir Drivers. Did it work ? Why ?
  • Didn't work. Directory not empty
  1. Delete the folder Drivers
  • rm -r Drivers

Part 3: Wildcards

  1. Create a new folder named wildcards, and cd to it.

     mkdir wildcards
     cd wildcards
    
  2. Create 5 new folders: src, include, lib, img, Doc

     mkdir src include lib img Doc
    
  3. Create 7 new files: src/main.c, src/player.c, include/player.h, lib/zlib.c, img/hero.png, img/player.png, doc/README.txt, doc/test.c.

     touch src/main.c src/player.c include/player.h lib/zlib.c img/hero.png img/player.png doc/README.txt doc/test.c
    
  4. Use ls to print the details of the following:

    1. All folders whose name starts with a lowercase letter

       ls -d [a-z]*
      
    2. All folders whose name starts with an uppercase letter

       ls -d [A-Z]*
      
    3. All folders whose name ends in a vowel (a, e, i, o, or u)

       ls -d *[aeiou]
      
    4. All folders whose name does not end in a vowel

       ls -d *[^aeiou]
      
    5. All .c files in src folder

       ls src/*.c
      
    6. All .c files in all folders

       ls */*.c
      
    7. All files whose name starts with a p, which are in a folder whose name starts with an i.

       ls i*/[ap]*
      
  5. Now delete all .png files from all folders

     rm */*.png
    
  6. Using curlies we can create command line repeaters that are not bound to current file status. Try to execute the following: mkdir -p {a,b,c}/{1,2,3}. How many new folders were created ?

  7. Would that still work if you replaced {...} with [...] ? Why ?

Part 4: File Permissions

  1. cd to wildcards folder from previous part.

  2. Change permissions of src/main.c to: r--r--r-- using letter notation.

     chmod a=r src/main.c
    
  3. Change permissions of include/player.h to r-xrw--w- using numeric notation.

     chmod 562 include/player.h
    
  4. Change permissions of all files under Doc to rw-------, without changing permissions for the Doc folder itself.

     chmod 600 Doc/*
    
  5. Change permissions of lib folder and all files inside it to rwxrwxrwx.

     chmod -R 777 lib
    
  6. Create a new folder named test and a new file named secret inside test.

     mkdir test
     touch test/secret
    
  7. Change permissions of test to ---------. Can you delete just the file secret ? Can you delete test ?

     chmod 000 test
    
  8. Read about umask in man csh. Set the mask so all new files are created with permissions: ------r--.

     umask 773
    

Part 5: Links

  1. Create a new folder named links and cd to it.

     mkdir links; cd links
    
  2. Create 2 files: file1, file2. Inside file1 write names of some programming languages you like, and inside file2 write the names of some programming languages you don't like.

     echo perl > file1
     echo python > file2
    
  3. Create file file3 as a symbolic link to file1

     ln -s file1 file3
    
  4. Create file file4 as a hard link to file2

     ln file2 file4
    
  5. Move file3 to /tmp folder. Can you still read its contents using cat ?

     mv file3 /tmp
    
  6. If the answer was no, create a new file3 as a symbolic link to file1, that would survive the move to /tmp.

     ln -s `pwd`/file1 file3
     mv file3 /tmp
    
  7. Print out the contents of the first file using cat file3.

     cat tmp/file3
    
  8. Delete file1.

     rm file1
    
  9. Can you still see its contents through file3 ?

     no
    
  10. Now move file4 to your home folder. Can you still see the contents of file2 using only file4 ?

    mv file4 ~
    cat ~/file4
    
  11. Use ls to find the inode number of files: file2, file3, file4.

    ls -li ~/file4 /tmp/file3 file2
    

Part 6: vim

  1. Try to figure out what the following key sequences do in normal mode: gg, dgg, G, dG, 7G, f<letter>, F<letter>, /<word>.
  • gg: go to start of file
  • dgg: delete till start of file
  • G: go to end of file
  • dG: delete till end of file
  • 7G: go to line 7
  • f: go forward in line till letter is found
  • F: go backward in line till letter is found
  • /word: search word in file
  1. Copy the file /etc/passwd to your home folder
  • cp /etc/passwd ~
  1. Start vim on the new copy
  • vim ~/passwd
  1. Delete the first line
  • Gdd
  1. Move the next 4 lines to the end of the file
  • 4ddGp
  1. Save and quit (use ZZ), or quit without saving with ZQ.
  • ZZ
  1. Try to figure out what the following key sequences do in insert mode: ^u, ^y, ^t, ^n
  • ^u: delete typed text
  • ^y: copy from line above
  • ^t: insert tab
  • ^n: auto complete
  1. Start vim on existing file
  • vim ~/passwd
  1. Delete first paragraph
  • ggd}
  1. Write a new first paragraph telling 5 things you love about vim
  • imodal editing is cool<Esc>yy5p
  1. Save and Quit (using :wq or ZZ)

  2. Try to figure out what the following key sequences do in vim command line: :!ls, :%!tac, %!sort

  • !ls - run ls
  • %!tac - run tac on buffer and send result back to the editor
  • %!sort - run sort on buffer and send result back to the editor
  1. Create a new key mapping so pressing ^s vim will save the file
  • inoremap <C-s> <Esc>:w<cr>a
  1. Create a new key mapping so pressing ^x vim will save and exit
  • inoremap <C-x> <Esc>ZZ
  1. Insert both new key mappings to your .vimrc file

Part 7: Redirections and Pipes

  1. who -u prints out idle time for each connected user. Print out the 3 users who were idle the longest time.

      who -u | tr -s ' '  | grep -v old | grep -v \. | sort -t ' ' -k 6 | head -3
    
  2. Print the number of files that have execute permission to their owner.

     ls -l | cut -c4 | grep x | wc -l
    
  3. Print the number of files that have execute permissions to their owner, group and others.

     ls -l | cut -c4,7,10 | grep xxx | wc -l
    
  4. Print the number of files that were modified on a given date.

     ls -l | tr -s ' ' | cut -d' ' -f5,6 | grep 'Jan 21' | wc -l
    
  5. Print a list of all files modified TODAY.

     ls -l | tr -s ' ' | cut -d' ' -f5,6 | grep '`date +"%b %d"`' | wc -l
    
  6. /sbin/ifconfig prints a lot of information about your network connections. Use filters to get only the IP address of the host.
    Remember 127.0.0.1 is just a loopback IP, so we should ignore that one.

      ifconfig |grep inet|grep -v inet6|grep -v 127.0.0.1
    
  7. Print a list of all Saturday dates on May 2005.

     cal 5 2005| cut -c19-20
    
  8. ps -ef prints a list of all processes in the system. Find how many processes match the name csh.

     ps -ef | grep csh | grep -v grep
    
  9. The command curl http://graph.facebook.com/103113856395914 prints out information about the facebook page "Unix". Find out how many likes the page has.

     curl -s http://graph.facebook.com/103113856395914| rev | cut -d: -f1 | cut -c2-|rev
    

Part 8: Find

  1. Under your home directory, print all files and folders recursively that:

    1. Are owned by you

       find . -user `whoami`
      
    2. Are not owned by you

       find . -not -user `whoami`
      
    3. Their name ends with a '.c'

       find . -name '*.c'
      
    4. Their name starts with an a, e, i, o, or u

       find . -name '[aeiou]*'
      
    5. Weight above 10M

       find . -size +10M
      
    6. Were created more than 3 hours ago.

       find . -cmin +240
      
    7. Were modified in the past 2 days.

       find . -mtime +2
      
    8. Were not accessed in the past week.

       find . -ctime +7
      
  2. Create the following files: a.txt, b.txt, c.txt. Now use a single find command to create 3 backup files: a.txt.bak, b.txt.bak and c.txt.bak (as copies of the original files).

     find . -type f -exec cp '{}' '{}'.bak \;
    

Part 9: Regular Expressions

  1. Given the following lists of positive and negative words, type a regular expression that matches all words in positive, but doesn't math any of the words in negative.

    Positive Negative
    pit pt
    spot Pot
    spate peat
    slap two part
    respite

    Regexp: p.t

    Positive Negative
    rap them aleht
    tapeth happy them
    apth tarpth
    wrap/try Apt
    sap tray peth
    87ap9th tarreth
    apothecary ddapdg
    apples
    shape the

    Regexp: p.?t

  2. Write a regular expression to accept any binary string (only 0s and 1s)

     ^[01]+$
    
  3. A binary string represents an even number if it ends with a 0. Write a regular expression to match an even number represented as a binary string.

     ^[01]*0$
    
  4. Write a regular expression to accept any hexa-decimal string

     ^[0-9a-fA-F]+$
    
  5. Print all lines from ls -l which represent a folder

     ls -l | egrep '^d'
    
  6. Print all files and folders whose name starts with an uppercase letter and ends with a number.

     ls | egrep '^[A-Z].*[0-9]$'
    
  7. Print all files (no folders) which have execute permission to owner

     ls -l | egrep '^-..x'
    
  8. All lines from ls -l which start with a -, an l or a d

     ls -l | egrep '^[-ld]'
    
  9. All lines from ls -l that are longer than 50 characters

    ls -l | egrep '.{50}'
    
  10. All lines from ls -l that have an even length (בעלות אורך זוגי)

    ls -l | egrep '^(..)*$'
    

Part 10: Aliases and Startup Files

  1. Write the following aliases:

    1. ll => ls -l

    2. c => clear

    3. rm => rm -i

    4. cp => cp -i

       alias ll "ls -l"
       alias c clear
       alias rm "rm -i"
       alias cp "cp -i"
      
  2. Now try to overwrite an existing file with cp. Did you get a prompt?

     yes
    
  3. Next, use the unaliased version of cp to overwrite a file without the prompt (But don't unalias it).

     \cp /etc/passwd ~/copy
    
  4. Write the following aliases:

    1. count_files => print the number of files in current directory

    2. bysize => list all files ordered by sizes (from large to small)

    3. lmod => list all files modified in date (date is a date string from ls -l)

    4. ff => find a file by a partial name. For example, ff ba should print all files and folders whose name contains ba.

       alias count_files "find . -type f -maxdepth 1 | wc -l"
       alias bysize "ls -lS | egrep -v '^d'"
       alias lmod "ls -l | egrep "
       alias ff "find . -name '*'\!*'*'"
      

Part 13: Processes and Jobs

  1. Run the program xeyes in a terminal.

     xeyes
    
  2. From the same terminal, freeze xeyes with ^Z.

  3. List all jobs in the terminal. Can you find xeyes ?

     jobs
    
  4. Send xeyes to resume in the background

     bg
    
  5. Terminal xeyes using kill

     kill %1
    
  6. The command ps -u <user> prints out all processes running on the server owned by user. Terminal all processes named vim running under your user, in a single command.

     ps -ef | grep vim | awk '{print $2}' | xargs kill -9
    

Part 14 - awk

  1. Add a blank line after each line of input
ls -l | awk '{ printf("%s\n\n", $0) }'
  1. Print a '> ' in the beginning of each line
ls -l | awk '{ printf("> %s\n", $0) }'
  1. Use awk that take a file name as input and performs:
    1. If a line starts with #, replace each character with a -
    2. For all other lines, replace each character with a . (print result to screen)
cat /etc/shells | awk '/^[^#]/ { gsub(".", "-", $0) } /^#/ { gsub(".", ".", $0) } { print }'
  1. Replace the first and last word in every line
  2. The command /sbin/ifconfig prints out information about network interfaces. Here's a sample output for the command:

en3: flags=8963 mtu 1500
        options=60
        ether 32:00:18:24:c0:00
        media: autoselect 
        status: inactive
p2p0: flags=8843 mtu 2304
        ether 06:38:35:47:96:24
        media: autoselect
        status: inactive

Use awk to parse the information generated by ifconfig and create an information file for each network interface. For example the above interface should produce two files: first is named en3.info and has the en3 block, and the second is named p2p0.info and has the second block

/sbin/ifconfig | awk '/^[a-z]/ { fname = $1 } { print > fname }'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment