jeudi 30 janvier 2020

Suggestion to Reduce Number of code lines - Unix

I am trying to update the file permission oftest_1.txt available as content inside the main file test.txt based on the value available in the variable IN. Below script will help to modify the content as per my requirement. But I need to reduce the number of lines of code. so could you suggest any way to reduce the number of lines and achieve the same output.

Code

#!/bin/bash
IN=750
Input=test.txt
Char_one=$(echo $IN | cut -c 1)
Char_two=$(echo $IN | cut -c 2)
Char_three=$(echo $IN | cut -c 3)

if [[ "$Char_one" == "7" ]]; then 
 Char_one="rwx"
elif [[ "$Char_one" == "6" ]]; then 
 Char_one="rw-"
elif [[ "$Char_one" == "5" ]]; then 
 Char_one="r-x"
elif [[ "$Char_one" == "4" ]]; then 
 Char_one="r--"
elif [[ "$Char_one" == "3" ]]; then 
 Char_one="-wx"
elif [[ "$Char_one" == "2" ]]; then     
 Char_one="rwx"
elif [[ "$Char_one" == "1" ]]; then     
 Char_one="-w-"
elif [[ "$Char_one" == "0" ]]; then     
 Char_one="---"
fi

if [[ "$Char_two" == "7" ]]; then 
 Char_two="rwx"
elif [[ "$Char_two" == "6" ]]; then 
 Char_two="rw-"
elif [[ "$Char_two" == "5" ]]; then 
 Char_two="r-x"
elif [[ "$Char_two" == "4" ]]; then 
 Char_two="r--"
elif [[ "$Char_two" == "3" ]]; then 
 Char_two="-wx"
elif [[ "$Char_two" == "2" ]]; then     
 Char_two="rwx"
elif [[ "$Char_two" == "1" ]]; then     
 Char_two="-w-"
elif [[ "$Char_two" == "0" ]]; then     
 Char_two="---"
fi

if [[ "$Char_three" == "7" ]]; then 
 Char_three="rwx"
elif [[ "$Char_three" == "6" ]]; then 
 Char_three="rw-"
elif [[ "$Char_three" == "5" ]]; then 
 Char_three="r-x"
elif [[ "$Char_three" == "4" ]]; then 
 Char_three="r--"
elif [[ "$Char_three" == "3" ]]; then 
 Char_three="-wx"
elif [[ "$Char_three" == "2" ]]; then   
 Char_three="rwx"
elif [[ "$Char_three" == "1" ]]; then   
 Char_three="-w-"
elif [[ "$Char_three" == "0" ]]; then   
 Char_three="---"
fi  

while IFS= read -r line;
  do
  j=1
  perm_1=$(echo $line | awk '{print $1}' | cut -c 2-4)
  perm_2=$(echo $line | awk '{print $1}' | cut -c 5-7)
  perm_3=$(echo $line | awk '{print $1}' | cut -c 8-10)   
  Def_Chmod=$(echo "$line" | sed -i "$j s/$perm_1$perm_2$perm_3/$Char_one$Char_two$Char_three/;" "$Input")                
    j=$((j+1))
  done <"$Input"

test.txt

-rwxrwxr-x test_1.txt

Output

Content of the test.txt file after the execution of the above code.

-rwxr-x--- test_1.txt

Aucun commentaire:

Enregistrer un commentaire