Kristoffer
Kristoffer

Reputation: 486

Trying to create a string in awk, complains about division with zero

I am trying to create a script to automagically create symlinks to all my folders under a specific folder, this should ot be to hard to do but for some reason my variables are passed around really odd inside this oneline script.

#!/bin/bash
# ----------------------------------
# --------- TotalKrill -------------
# ----------------------------------
# Script to create symlinks to my clouded folder in my home directory by listing all  folders/files in the cloudfolder and then creating symlinks in destfolder
# 
myname=`whoami`
searchfolderdir=/home/$myname/
searchfoldername=ownCloud
destfolder=~/
Target=$searchfolderdir$searchfoldername/

ls -1 $searchfolderdir$searchfoldername | awk {'print ln -fs $Target$0 $destfolder/$0'} #|sh 

But I get an output : awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted

Can anyone please point me on a better approach or tell me how to fix this script? the "| sh" is commented out so i can get a correct line before running.

On a ubuntu 12.10 x64 box trying to get it working.

Upvotes: 0

Views: 657

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85785

What you need is (syntactically at least):

awk -v t="$Target" -v d="$desfolder" '{print "ln -fs",t$0,d"/",$0}' 

Notes:

  • If you don't want the division operator but the literal char / you need to inclose it in double quotes.

  • Strings need enclosing in double quotes in awk like the string ln -fs

  • You need to pass shell variables to awk using the -v option.

  • You should always quote your variables.

  • The curly braces that in-close the block need to be inside the single quotes.


Adding a couple of other fixes like using find to return only directories:

#!/bin/bash

myname=$(whoami)
dir="/home/$myname/"
folder="myCloud"
destination="~/"
target="${dir}${folder}"

find "${target}" -maxdepth 1 -type d -print | 
awk -v t="$target" -v d="$destination" '{print "ln -fs",t$0"/",d}' 

Upvotes: 1

Related Questions