Question & Answer: Bash script, unix…..

Bash script, unix

Script that receives multiple arguments arg1, arg2, arg3… And renames according to swap even and odd. For example, fooA fooB food fooD fooE would rename fooA to fooB, fooC to fooD, fooE to fooF, and so on. Assume all files exist, up to 50 arguments.

Check the number of arguments first to ensure an even amount of arguments.

Write the script

#! /bin/sh

Expert Answer


n=$# # Total no. of arguments
r=$(( $n % 2 )) # Getting remainder after division by 2
if [ $r -eq 0 ] # If no. of arguments is even
i=1 # i iterates from 1 to n-1
while [ $i -lt $n ];do
j=$(( $i + 1 )) # j holds i + 1
# Swapping the two files
eval “mv ${$i} temp” # Renaming first file into temp
eval “mv ${$j} ${$i}” # Renaming second file into first
eval “mv temp ${$j}” # Renaming temp into second
i=$(( $i + 2 )) # Incrementing i by 2
echo “File renaming done.”
echo “Odd number of files”


Question & Answer: Bash script, unix..... 1


Question & Answer: Bash script, unix..... 2

Still stressed from student homework?
Get quality assistance from academic writers!