[SOLVED]bash: assign a command output to a variable

EDIT: Sorry, got the solution - the variable was good, I just forgot a "do" in a "for" loop.... Sorry
Hi erveryone.
I'm just starting to learn the basics of bash scripting, and I got a problem assigning the output of a command to a variable, and i keep getting syntax errors...
var=$(cut -d: -f1 foo)
echo $var
A google search gives many different ways to do this, but without better results..
var=`cut -d: -f1 foo`
var="`cut -d: -f1 foo`"
Any idea what I'm doing wrong?
Thanks!
Last edited by haiku (2012-02-01 14:19:00)

haiku wrote:var=$(cut -d: -f1 foo)
var=`cut -d: -f1 foo`
The first two are both 'right' (in bash) but the first is the preferred syntax (in bash).  I think sh only understands the second.  I've never used quotes in a situation like this, but it seems to work.  That said, maybe the problem is the command itself, because all variations work for me:
$ cat foo
genmon1a:genmon1b
genmon2:genmon3:genmon4
$ cut -d: -f1 foo
genmon1a
genmon2
$ D=$(cut -d: -f1 foo)
$ echo $D
genmon1a genmon2
$ D=`cut -d: -f1 foo`
$ echo $D
genmon1a genmon2
$ D="$(cut -d: -f1 foo)"
$ echo $D
genmon1a genmon2
$ D="`cut -d: -f1 foo`"
$ echo $D
genmon1a genmon2
It might help if you could give us some of the 'bigger picture' too: what you are trying to do overall, the contents of foo, what you are trying to do with the variable, etc.
Last edited by alphaniner (2012-02-01 14:31:01)

Similar Messages

  • [SOLVED] bash: $'\302\240grep': command not found [frequent CLI error]

    For the past several days I've been getting the following error frequently on the command line:
    bash: $'\302\240grep': command not found
    I think I'm only getting this error in response to commands that are piped to grep, such as the following:
    $ ps -ef | grep xyz
    or
    $ locate | grep abc
    However, I don't think I've gotten the error if I type the same commands as above, but without the space between '|' and 'grep'.  And, although the error is frequent, it doesn't happen every time; it is seemingly random.
    Anybody else experiencing this?  Any idea what might be causing it? 
    I'm using rxvt-unicode as my terminal.
    Jay
    Last edited by jt512 (2011-04-06 04:38:56)

    anonymous_user wrote:Post your ~/.bashrc
    # Check for an interactive session
    [ -z "$PS1" ] && return
    function timer () {
    at -f /home/jay/.timercmd now + $1 min
    function cpufs () {
    sudo cpufreq-set -c 0 $1 $2
    sudo cpufreq-set -c 1 $1 $2
    alias ls='ls --color'
    alias kc='~/scripts/kc.py'
    alias diff='colordiff'
    alias s2ram='sudo s2ram -f'
    alias grep='grep --color=always'
    alias Terminal='Terminal -T Terminal'
    alias emacsnw='emacs -nw -f menu-bar-mode'
    alias rm='rm -I'
    alias lpstd='lp -o "StpQuality=Standard"'
    alias paps='paps --paper letter --font="Courier 10"'
    alias mp='mplayer'
    alias mps='mplayer -softvol-max 600'
    alias mysql='$HOME/scripts/mysql'
    if [ $TERM = 'linux' -a $SHELL = '/bin/bash' ] ; then
    PS1='\033[?17;0;40c[\u@\h \W]\$ '
    else PS1='[ \[\e[0;32m\]\u@\h\[\e[m\] \[\e[0;31m\]\W\[\e[m\] \[\e[m\]]\[\e[0;32m\] \$ \[\e[m\]'
    fi
    eval `dircolors -b`
    # Allow tab completion for sudo'ed commands
    complete -cf sudo
    export PATH=$PATH:~/.local/usr/bin
    export EDITOR="vim"
    export BROWSER='conkeror:uzbl-browser:firefox'
    export GREP_COLOR="1;33"
    export LESS_TERMCAP_mb=$'\E[01;31m'
    export LESS_TERMCAP_md=$'\E[01;31m'
    export LESS_TERMCAP_me=$'\E[0m'
    export LESS_TERMCAP_se=$'\E[0m'
    export LESS_TERMCAP_so=$'\E[01;44;33m'
    export LESS_TERMCAP_ue=$'\E[0m'
    export LESS_TERMCAP_us=$'\E[01;32m'
    export SWEAVE_STYLEPATH_DEFAULT="TRUE"

  • [Solved] Bash: Want to supress output but still have it recorded

    I'd like to run a test, have it known but the output not to show.  How do I do this?
    [[ -z $(ls -1 screencast-[0-9][0-9][0-9][0-9]*) ]] && echo hi
    If I send it to /dev/null it doesn't get recorded, what do I do?
    Last edited by Gen2ly (2012-08-23 14:08:00)

    Send it to a file - or a variable.
    *think I must be missing something*
    Oh, after reading better I think I get it, though the answer would be the same.  Do you only want the return code of the command used for the test while other output is ignored?  Various options depending on your need:
    commmand >/dev/null
    [[ $? -eq 0 ]] && conditionally-executed-command
    [[ `command >/dev/null` ]] && conditionally-executed-command
    command > ~/my.log
    VARIABLE_LOG=$(command)
    Last edited by Trilby (2012-08-23 12:46:26)

  • Assigning simple Java output to a Variable

    Is it possible to have a variable in a package that gets assigned a value from a call to core Java method so that I can use that variable across all interfaces in the package. Here's what I'd like to see (pseudo code)
    --Package execution start
    --Assing java.util.UUID.randomUUID().toString() to variable "UUID"
    --Run interface 1
    --map #UUID into a field
    -- Run interface 2
    -- map same #UUID value into a field
    -- End execution start
    Thanks,
    Michael

    yes it is possible. You have to create one odi procedure for this. Inside odi procedure take the technology as java beanshell and write the code like below.
    <@
    //java codes hoes here
    String java_v="Bhabani";
    //java codes hoes here
    @>
    Now drag this procedure into odi package. next drag another odi variable to odi package. In set mode assign the java variable to the odivariable as follows.
    <@=java_v@>
    Its done. You are reeady to use the odi variable everywhere you need in the same package.
    Bhabani
    http://dwteam.in

  • [SOLVED] Make Bash Completion Error (Command Not Found)

    When attempting to tab complete the `make` command, I am met with the following when I hit tab:
    $ make s[tab]bash: 23:set: command not found
    Strangely, if I continue hitting tab, it seems to work eventually, but with the same error popping up:
    $ make s[tab]bash: 23:set: command not found
    ched.[tab]bash: 23:set: command not found
    [tab]bash: 23:set: command not found
    sched.1.gz sched.tar.gz
    $ make sched.
    I've never seen anything like this.  I've tried reinstalling bash completion and make to no success.  The Makefile itself is fine and functional.  Other programs' bash completions seem to work just fine.  Help!
    Last edited by goakley (2014-03-23 13:56:50)

    It seems the problem no longer occurs.  The only change that seems to have happened is a bash-completion upgrade that happened yesterday.  I'm a bit disappointed to have not found the actual issue.

  • [solved] bash errors

    Howdy, first post here, installed arch last week after many years on debian based systems.
    I promise I have read the wiki on bash & have googled for hours & I cannot find what is generating these errors in the terminal every time a terminal is opened.
    bash: N: command not found
    bash: $!ba: command not found
    bash: s/n/: No such file or directory
    I can't recall at what point this error started to appear.  I have checked .bashrc, my bash aliases, I am stumped.
    My .bashrc :
    # ~/.bashrc
    # If not running interactively, don't do anything
    [[ $- != *i* ]] && return
    alias ls='ls --color=auto'
    PS1='[\u@\h \W]\$ '
    export LANG=en_GB.utf8
    export LC_MESSAGES="C"
    export LC_ALL=en_GB.utf8
    export EDITOR=nano
    source /usr/share/doc/pkgfile/command-not-found.bash
    # Alias definitions.
    # You may want to put all your additions into a separate file like
    # ~/.bash_aliases, instead of adding them here directly.
    # See /usr/share/doc/bash-doc/examples in the bash-doc package.
    if [ -f ~/.bash_aliases ]; then
        . ~/.bash_aliases
    fi
    Last edited by cl00t (2013-07-25 18:33:50)

    Great :-)
    Next time when pasting configs, code or command output, please use [ code ] tags https://bbs.archlinux.org/help.php#bbcode
    like this
    It makes the code more readable and - in case of longer listings - more convenient to scroll through.
    Please remember to mark the thread as solved https://bbs.archlinux.org/viewtopic.php?id=130309

  • Assigning stored procedure output value to java variable

    I have one stored procedure which is having ref cursor as the output parameter.
    How to assign refcursor value to my java variable?

    cstmt.registerOutParameter(1, OracleTypes.CURSOR);
    cstmt.execute()
    ResultSet rs = (ResultSet)cstmt.getObject(1);
    ==
    Ashok

  • How to copy the linux command output to the clipboard xclip is not working?

    Friends,
    OS: OEL 5.5
    i want to copy the command output to the clipboard.
    so, which rpm i have to install?
    i tried with xclip rpm its not working...
    xclip /etc/sysctl.conf
    but its not working, not only the above command but all the commands of xclip is not working.
    so, can anybody suggest me a solution?
    thanks

    i have already tried that...
    below is thru the secureCRT terminal
    [root@rac1 /]# cat /etc/sysctl.conf | xclip
    Error: Can't open display: (null)below is directly from the os
    [root@rac1 ~]# vi tet
    [root@rac1 ~]# tail -100 /var/log/messages | xclip
    [root@rac1 ~]# vi test
    [root@rac1 ~]# cat /etc/sysctl.conf | xclip
    [root@rac1 ~]# vi test
    [root@rac1 ~]# echo 'hello' | xclip
    [root@rac1 ~]# vi testEdited by: OraDB on Aug 19, 2012 10:33 AM

  • How to? multiline label containing exact system command output

    Background info: I'm triggering a system command to display memory utilization. As you know, the "free" linux command displays many lines of text one after the other. It is similar to the mem command used in Window$.
    I want to have a label displaying the command output as it is: multiple lines. Just like you see it in the console. I want to mirror whatever comes up on console after executing free from java.
    Using html tags won't work out for me in this particular situation. It just doesn't do the trick. Still displays the LAST line of command output with or without html tags.
    any ideas? it doesn't have to be a label. It can be anything as long as it works.
    Again, as it is, it just displays the last line of the command output
    //events will trigger every second
    Timer t = new Timer(1000, new ActionListener(){
          public void actionPerformed(ActionEvent event)
    //determine memory utilization.
            String cmd = "free -m";
        try {
         String line;
         Process p = Runtime.getRuntime().exec(cmd);
         BufferedReader input =
           new BufferedReader
             (new InputStreamReader(p.getInputStream()));
         while ((line = input.readLine()) != null) {
           label.setText(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
        t.start();

    got it. thanks.
    String cmdMem = "free -m -t -o" ;
          try {
            String lineMem ;
            String outputMem = "" ;
            Process procMem = Runtime.getRuntime ().exec ( cmdMem ) ;
            BufferedReader input =
                new BufferedReader
                ( new InputStreamReader ( procMem.getInputStream () ) ) ;
            while ( ( lineMem = input.readLine () ) != null ) {
              outputMem = ( lineMem + "\n" ) ;
              jTextAreaSystemResourcesOutput.append ( outputMem ) ;
            input.close () ;
          catch ( Exception err ) {
            err.printStackTrace () ;
          }

  • Assign Form and Output Program for Purchase Order

    Hi,
    in SPRO, Assign Form and Output Program for Purchase Order I see the following data:
    -  IMG Activity  Assign Form and Output Program for Purchase Order
        -  View Maintenance: Data                                                                               
    -  VV_TNAPR_EF                                                                               
    -  TNAPR                                                                               
    -  007ZNEU2EF
    What is 007ZNEU2EF ? 
    Yours faithfully

    I dont have enough knowledge on this one. However i will try to clarify this
    007 i think its a version
    ZNEU2 its a Process type
    EF Purchase order

  • Sample Command Output of show chassis inventory for CSS

    Hi,
    I am trying to get a sample command output of "show chassis inventory" for:
    CSS 11501
    CSS 11503
    CSS 11506
    Can anyone help?
    Thanks in advance.
    Mike

    Hi Mchi,
    When I use the command: show chassis inventory. I found :
    Slot  Module                           Serial
    1     CSS5-SCM-2GE F0   JABxxxxxxx
    2     CSS5-IOM-2GE E0   JAB08xxxxxx
    3     CSS5-IOM-8FE F0   JAB0xxxxxxx
    4     CSS503-SM-INT     JAB09xxxxxxx
    this is the switch fabric module that connects the other modules.
    This is an internal module and it can't be removed/replaced.
    Use the show chassis command to display a chassis configuration for the CSS. The syntax and options for this command are as follows:
    •show chassis - Displays a summary of the chassis configuration.
    •show chassis slot number  - Displays the operational parameters for a slot in a CSS 11503 or CSS  11506 chassis. Enter an integer value for the chassis slot number.
    •show chassis verbose - Displays detailed information about the chassis configuration.
    •show chassis flash - Displays the operational and locked Flash software code on the CSS  11501, and the CSS 11503 or CSS 11506 SCM and I/O modules. An asterisk  (*) character before a Flash version of code and build number indicates  that it is active.
    •show chassis inventory - Displays the physical configuration of the CSS including part and serial numbers.
    •show chassis session-processors - Displays the weight and power summary of the session processors in the CSS chassis.
    CSS11506# show chassis inventory
    Chassis Inventory:
    Product Name:    CSS11506-2AC E0    SW Version:        07.50.1.05s
    Serial Number:   JAB09xxxxxx        Base Mac Address:  00-13-80-37-xx-xx
    Slot  Module            Serial
    1     CSS5-SCM-2GE F0   JAB0915xxxx
    2     CSS5-SCM-2GE F0   JAB0914xxxx
    3     CSS5-SSL-K9 F0    JAB0848xxxx
    4     CSS5-IOM-2GE E0   JAB0808xxxx
    7     CSS506-SM E0      JAB0911xxxx
    8     CSS506-SM E0      JAB0911xxxx
      Even a "show chassis verbose" command does  not indicate the presence of a GBIC.  It shows the Operational Status of  a port as "online" whether there is a GBIC installed or not.  For  example, in the output below Slot 4 has a GBIC installed in port 4/1,  but 4/2 is empty:
    CSS11506# sho chassis verbose
    Configuration for CSS11506-2AC E0:
    Product Name:    CSS11506-2AC E0    SW Version:        07.50.1.05s
    Serial Number:   JAB0916xxxx        Base Mac Address:  00-13-80-37-xx-xx
    Module(s) Found:                   6
    Power Supplies(s) Found:           2
    Fan(s) Found:                      3
    Slot/SubSlot  Operational                  Locked
       1/1        *07.50.1.05                       07.40.1.03
       2/1        *07.50.1.05                       07.40.1.03
       3/1        *07.50.1.05                       07.40.1.03
       4/1        *07.50.1.05                       07.20.2.06
    Slot Number:                       1  Type:       CSS5-SCM-2GE F0
    Serial Number:           JAB0915xxxx  Number of Ports:          2
    Operational Status:          primary
    Port Number:                      1  Port Name:          SCM-2GE
    Operational Status           online
    Port Number:                      2  Port Name:          SCM-2GE
    Operational Status           online
    Slot Number:                       2  Type:       CSS5-SCM-2GE F0
    Serial Number:           JAB0914xxxx  Number of Ports:          0
    Operational Status:           backup
    Slot Number:                       3  Type:        CSS5-SSL-K9 F0
    Serial Number:           JAB0848xxxx  Number of Ports:          0
    Operational Status:          primary
    Slot Number:                       4  Type:       CSS5-IOM-2GE E0
    Serial Number:           JAB0808xxxx  Number of Ports:          2
    Operational Status:          primary
    Port Number:                      1  Port Name:          IOM-2GE
    Operational Status           online
    Port Number:                      2  Port Name:          IOM-2GE
    Operational Status           online
    Slot Number:                       7  Type:          CSS506-SM E0
    Serial Number:           JAB0911xxxx  Number of Ports:          0
    Operational Status:       powered-on
    Slot Number:                       8  Type:          CSS506-SM E0
    Serial Number:           JAB0911xxxx  Number of Ports:          0
    Operational Status:       powered-on
    end of buffer.
    Maybe you can use "show tech"
    HTH
    Sachin

  • Command output redirect question

    Hi guys,
    I am putting in a kron function to transfer the command output from all the switches and routers on our network to a tftp server.
    I have the kron occurence and policy lists set up the way I want them and have tested the redirection of the command line output to the server.
    The problem I have is that I want to back up the switches 3 or 4 times once a week to compare the configs to make sure that no unwanted changes are being made over the course of the month.
    Is there a way to use a variable to change the file name when it redirects? Currently when the occurence runs the file modified time on the tftp server changes but the output doesnt append as I had hoped it would, i.e one file having the config copy in to the file over and over.
    Thanks for your help

    You might want to consider the built-in Config Archive feature instead of kron.  With Config Archive, you can periodically take backups of your config (even to a network server), and you can adjust the filenames using either date or hostname (or both).  Check out the documentation at http://www.cisco.com/en/US/docs/ios/12_3t/12_3t7/feature/guide/gtrollbk.html#wp1100253 for more details.
    In addition to Config Archive, you also have the option of going with the Embedded Event Manager.  EEM also has a cron feature which will allow you to run CLI commands periodically.  Depending on your IOS version, it may be possible to do what you want using a simple EEM applet, or you might have to use a Tcl script policy.  More on EEM can be found at http://www.cisco.com/en/US/docs/ios/netmgmt/configuration/guide/nm_eem_overview_ps10592_TSD_Products_Configuration_Guide_Chapter.html .
    All that said, most TFTP servers have a security requirement that a file must exist on the server before one can write to it.  Therefore, if you try and create new files (i.e. a new file each day), the TFTP server may reject the WRITE REQUEST unless a file with that name already exists.  In light of that, you may need to use something like SCP or FTP instead.

  • How to Save Command Output to Flash on ASA 8.4

    Hi,
    I nice easy one for you guys.
    How do you save the command output from the CLI  to a file on flash?
    With IOS, I would normally use a pipe command to redirect to tftp, but the ASA doesn't support this as far as I can tell. As a work around I was thinking I could save the output to flash and then tftp that file off the ASA.
    Thanks,
    Paul

    Hi Jennifer,
    Thanks for your help. I do use this feature at the moment, but I find every break in the output (where you need to hit space to see more) gets recorded which leaves the file quite messy. I usually have to edit the file afterwards so it reads clearly.
    I wondered if there is a way for the asa to write the output directly?
    Thanks,
    Paul

  • TOP  command output

    Hi,
    Can anybody describe the following TOP Command output...
    ==========================================
    Tasks: 197 total, 1 running, 196 sleeping, 0 stopped, 0 zombie
    Cpu(s): 12.0% us, 0.7% sy, 0.0% ni, 71.8% id, 15.5% wa, 0.0% hi, 0.0% si
    Mem: 4147796k total, 4120904k used, 26892k free, 25708k buffers
    Swap: 8191992k total, 160k used, 8191832k free, 3624432k cached
    4615 root 16 0 54320 15m 5952 S 24 0.4 4:41.11 X
    1915 oratest 16 0 923m 620m 485m S 20 15.3 17:09.41 oracle
    1730 oratest 16 0 385m 64m 23m S 4 1.6 0:54.07 java
    1912 oratest 15 0 23516 9.9m 5368 S 1 0.2 0:36.71 sqlplus
    1726 oratest 16 0 385m 64m 23m S 1 1.6 0:03.35 java
    1913 oratest 16 0 385m 64m 23m S 1 1.6 0:13.00 java
    2135 oratest 16 0 2448 1028 760 R 1 0.0 0:00.13 top
    1887 oratest 15 0 689m 23m 21m D 0 0.6 0:20.74 oracle
    1 root 16 0 3468 592 504 S 0 0.0 0:01.06 init
    2 root RT 0 0 0 0 S 0 0.0 0:00.04 migration/0
    3 root 34 19 0 0 0 S 0 0.0 0:00.00 ksoftirqd/0
    4 root RT 0 0 0 0 S 0 0.0 0:00.03 migration/1
    5 root 34 19 0 0 0 S 0 0.0 0:00.00 ksoftirqd/1
    6 root RT 0 0 0 0 S 0 0.0 0:00.04 migration/2
    7 root 34 19 0 0 0 S 0 0.0 0:00.00 ksoftirqd/2
    8 root RT 0 0 0 0 S 0 0.0 0:00.03 migration/3
    9 root 34 19 0 0 0 S 0 0.0 0:00.00 ksoftirqd/3
    10 root 5 -10 0 0 0 S 0 0.0 0:00.00 events/0
    11 root 5 -10 0 0 0 S 0 0.0 0:00.00 events/1
    12 root 5 -10 0 0 0 S 0 0.0 0:00.00 events/2
    13 root 5 -10 0 0 0 S 0 0.0 0:00.00 events/3
    14 root 5 -10 0 0 0 S 0 0.0 0:00.00 khelper
    15 root 15 -10 0 0 0 S 0 0.0 0:00.00 kacpid
    ================================================
    Why it is showing the Memory Free is 26 MB only...
    Only one Database is running on this Machine SGA is around 600MB only.....
    Why it is showing 26 MB Free of memory ....Can anybody please describe the TOP Command output.....

    Hi, this doest look too good... " Swap: 8191992k total, 160k used"
    this means you'r using some of you'r swap, "25708k buffers" and not becouse of you'r buffers.
    try using ps -ef or top ( and sort by memory by hitting "m" ) and search for the process that uses you'r memory.

  • What keys to assign Key Commands to

    Is there anyone out there that has really got a good system for assigning Key Commands to groups of keys? My KC system has developed sort of spasmodically as I have got to know the Logic over the years.. and without proper 'town planning' things are getting over crowded on my Apple Keyboard.
    I would appreciate comments from anyone who has a 'logical' mind who thinks they have a good system/choice for which keys to programme groups of key commands for ease of workflow. In particular I would be interested in:
    - Score Editor
    - Midi writing
    - Automation
    along with a word about favourite key commands
    thanks in advance
    MS

    Suggest orienting as many of your key commands on the LH side of the keyboard so that you can keep your RH hand on the mouse.
    The following is just a sampling of my k/c assignments; at this point I've been using these so long that I couldn't tell you if any of them resemble the factory k/c assignments, but anyway, here's a short list that don't use any modifier keys:
    F1 = event editor (lists)
    F2 = matrix/piano roll (within arrange)
    F3 = score editor (arrange)
    right below that...
    1 = event editor (opens separate window)
    2 = piano roll (sep. window)
    3 = score editor (sep. window)
    ESC = close window
    Q = quantize
    A = catch on/off
    V = toolbox
    D = MIDI out toggle (in editors)
    C = cycle
    H = hyperdraw autodefine
    F = continue (need to press it 2x to play when Logic is stopped)
    B = browser (media)
    L = library
    X = set locators to region and play
    Note how except for "H" and "L" (a new addition for L8) they're all on the LH side of the keyboard, and no modifier keys needed.
    Some RH-oriented key commands include:
    \[ = set left locator w/o rounding
    ] = set right locator w/o rounding
    Those plus SHIFT give me the same functions but with rounding
    As for key commands with modifiers, you might want to set up a system for yourself where you reserve specific modifier keys (or combinations of modifiers) for certain categories of tasks. For example, you could reserve CNTRLSHIFTkey for score editor-specific commands, such as:
    D = defeat interpretation
    F = force interpretation
    B = beam selected
    U = unbeam selected
    . = add staccato to selected notes
    - = add tenuto to selected notes
    < = crescendo
    ">" = diminuendo
    ( = slur below
    ) = slur above
    # (actually, "3") = enharmonic shift #
    @ (actually, "2") = enharmonic shift b
    ...and so on... Note that these aren't all LH oriented, but I like the idea of using character shapes ("<" = cresc.) as mneumonics where possible.
    In general I'llI use CNTRLOPT+SHIFTCMD for "dangerous" (global) operations such as changing all tracks to READ or TOUCH. Speaking of automation...
    I have F9 programmed to turn plug-in automation on/off. But toggling this without having the automation prefs visible means that you'll be toggling this function in the blind. So I have F10 programmed to open the automation prefs panel.
    Ultimately I'd suggest that you set up your key commands so that they make sense to you.
    Message was edited by: iSchwartz

Maybe you are looking for