unix - Shell Script : Assign the outputs to different variables -


in shell script need assign output of few values different varialbes, need please.

cat file1.txt   uid: user1   cn: user 1   employeenumber: 1234567   absjobaction: hired   

i need assign value of each attribute different variables can call them them in script. example uid should assigned new variable name current_uid , when $current_uid called should give user1 , forth other attributes.
, if output not contain of attributes attribute value should considered "null". example if output not have absjobaction value of $absjobaction should "null"


this did array

#!/bin/bash    ifs=$'\n'   array=($(cat /tmp/file1.txt | egrep -i '^uid:|^cn:|^employeenumber|^absjobaction'))    current_uid=`echo ${array[0]} | grep -w uid | awk -f ': ' '{print $2}'`   current_cn=`echo ${array[1]} | grep -w cn | awk -f ': ' '{print $2}'`   current_employeenumber=`echo ${array[2]} | grep -w employeenumber | awk -f ': ' '{print $2}'`   current_absjobaction=`echo ${array[3]} | grep -w absjobaction | awk -f ': ' '{print $2}'`    echo $current_uid   echo $current_cn   echo $current_employeenumber   echo $current_absjobaction   

output sh /tmp/testscript.sh follows:

user1   user 1   1234567   hired   

#!/usr/bin/env bash  # assuming bash 4.0 or newer: create associative array declare -a vars=( )  while ifs= read -r line;      ## see http://mywiki.wooledge.org/bashfaq/001   if [[ $line = *": "* ]];  ## skip lines not containing ": "     key=${line%%": "*}           ## strip after ": " key     value=${line#*": "}          ## strip before ": " value     vars[$key]=$value   else     printf 'skipping unrecognized line: <%s>\n' "$line" >&2   fi done <file1.txt # or < <(ldapsearch ...)  # print variables read, demonstrate declare -p vars >&2  # extract , print single variable name echo "variable uid has value ${vars[uid]}" 

note must run bash yourscript, not sh yourscript.


by way -- if don't have bash 4.0, might consider different approach:

while ifs= read -r line;   if [[ $line = *": "* ]];     key=${line%%": "*}     value=${line#*": "}     printf -v "ldap_$key" %s "$value"   fi done <file1.txt # or < <(ldapsearch ...) 

will create separate variables of form "$ldap_cn" or "$ldap_uid", opposed putting in single associative array.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -