glossary-banner

Custom Script

Table of content

Introduction

What is a custom script, why use a custom script, when to use a custom script.

arrow

Where can Custom Scripts be Used?

How to write a custom script, key components of a custom script, common use cases for custom scripts, best practices for writing custom scripts, troubleshooting custom scripts, frequently asked questions .

Welcome to our comprehensive glossary on Custom Script! Get ready to dive into the exciting world of creating your own scripts to meet your specific needs. Whether you're a developer, an aspiring coder, or simply curious about custom scripts, this guide will provide you with the in-depth knowledge you need.

A Custom Script is a piece of code that is specifically written to perform a particular task or fulfill a unique requirement. Unlike pre-built scripts, which are more generic and standardized, custom scripts offer the flexibility to tailor the code to your specific needs. With custom scripts, you can truly take control and craft solutions that are perfectly suited to your situation.

There are several compelling reasons to choose a custom script over pre-built options. First and foremost, custom scripts offer increased flexibility and customization. They give you the power to shape the code according to your specific requirements and make it uniquely yours. Whether you're developing a website, creating a game, or automating a workflow, a custom script allows you to tailor the functionality to your exact needs.

Custom scripts can be used in a wide range of scenarios, whenever you need a solution that is specifically designed for your requirements. Some common situations where a custom script can be beneficial include:

  • Creating a unique user experience on a website
  • Automating repetitive tasks and workflows
  • Enhancing the functionality of existing software or applications
  • Processing and manipulating data in a customized way
  • Integrating and connecting different systems or services

Web Development

Custom scripts can be instrumental in web development. They allow developers to create specialized functions, interactive elements, and more, giving websites a unique and engaging feel. From user registration forms to complex animations, the possibilities are limitless with custom scripts.

Data Analysis

Data Analysis

In the field of data analysis , custom scripts are used to automate repetitive tasks, perform bulk operations, and tackle complex calculations. They can even be used to create advanced data visualization tools, giving analysts a way to gain valuable insights more efficiently.

Software Applications

Custom scripts often form an integral part of software applications. They can be used to automate various tasks, react to specific triggers, or even power the core logic of the application itself. This makes them a key tool for software developers.

Marketing Automation

In the world of marketing, custom scripts can be used to automate a wide range of activities. From sending out personalized emails to tracking user engagement, these scripts can help optimize marketing efforts and boost overall efficiency.

Server Maintenance

For IT professionals, custom scripts provide a way to automate routine server maintenance tasks. These scripts can perform a range of tasks, from backing up data and deleting old files, to monitoring server performance and sending alerts if something goes wrong.

Define Your Objectives

Before you begin writing your custom script, it's crucial to understand what you aim to achieve. Are you trying to automate a specific task, extract data, or perhaps build a new tool? Having clearly defined objectives ensures your script serves its intended purpose.

Understand Your Audience

A significant part of writing a successful custom script involves knowing who will use it. Your script will likely differ depending on whether your audience consists of fellow programmers, less tech-savvy users, or perhaps even a certain age group. Understand their needs and level of technology familiarity.

Choose the Right Language

The language you'll use for your custom script depends on several factors, like your proficiency level, the language's capabilities, and the nature of your task. For instance, Python may be best for data manipulation, while JavaScript might suit a web-based application.

Organize Your Code

Good organization is key to a successful script. This includes appropriately commenting your code, using clear variable names, and breaking down complex tasks into smaller functions or modules. This practice not only helps others understand your script, but it also makes it easier for you to debug and make changes in the future.

Test Thoroughly

Once you've written your script, it's essential to test it thoroughly. Check it under different conditions to ensure that it works as expected, and don't overlook edge cases. After finding any bugs or errors, make the necessary revisions and retest. Remember, a well-working script is the result of careful coding and rigorous testing.

Character Development

A vital component of any custom script is character development. This process involves creating interesting, relatable characters that drive the story forward. Their backgrounds, personalities, and motivations should be clearly defined and consistent throughout the story.

Plot Structure

The plot structure is the backbone of your script. It typically includes a beginning, middle, and end. The narrative should progress logically, with conflicts and resolutions that maintain engagement and suspense.

Good dialogue adds depth to the characters and moves the plot forward. It should sound natural and true to each character's voice. Spoken words can reveal a lot about a character's personality, beliefs, and emotions.

The setting establishes the time and place where the story happens. It provides context and often influences the characters and plot. Whether it's a bustling city or a quiet seaside town, the setting can be as important as a character.

Consistent themes can give your script depth and make it more impactful. A theme is a central idea or message that runs through your script. It could focus on anything from love and friendship to courage and redemption, depending on the story you want to tell.

Custom scripts have a wide range of applications across various industries and sectors. Here are a few common use cases to give you an idea of their versatility:

  • Website customization: Create unique, interactive, and personalized website experiences for users.
  • Data manipulation and transformation: Process and transform data from different sources to meet specific requirements.
  • Task automation: Automate repetitive tasks to save time and increase efficiency in workflows.
  • Game development: Create custom game mechanics, behaviors, and actions to enhance gameplay.
  • System integration: Connect and integrate different systems or services to streamline processes and data exchange.

To ensure that your custom scripts are efficient, maintainable, and error-free, here are some best practices to follow:

  • Use meaningful variable and function names to enhance code readability.
  • Break down complex tasks into smaller, manageable functions.
  • Properly comment your code to provide clarity and make it easier for others to understand.
  • Handle errors and exceptions gracefully to improve the script's robustness.
  • Regularly back up your code and use version control systems to track changes.

Running into issues with your custom script is part of the learning process. Here are a few common troubleshooting strategies:

  • Debugging: Use debugging tools and techniques to identify and fix coding errors or logic issues.
  • Check dependencies: Ensure that all required libraries or modules are properly installed and up to date.
  • Review documentation and forums: Consult official documentation and online communities for potential solutions.
  • Break down the problem: If the script is complex, isolate the problematic part and test it separately.
  • Seek help: Don't hesitate to reach out to experts or the developer community for assistance if needed.  

Can I use a custom script on my website?

Yes, you can! Custom scripts allow you to enhance your website's functionality and create unique user experiences.

Do I need to be a programmer to write a custom script?

Not necessarily! Basic programming knowledge is helpful, but there are plenty of resources available to help you learn and write your own custom scripts.

How do I know which programming language to use for my custom script?  

Choose a programming language based on your project requirements and familiarity. Popular options include JavaScript, Python, and PHP.

Can I use custom scripts to automate tasks in my workflow?

Absolutely! Custom scripts are great for automating repetitive tasks, saving you time and increasing efficiency in your workflow.

Are there any best practices for writing custom scripts?

Yes! Use meaningful names for variables and functions, break tasks into smaller functions, comment your code, handle errors gracefully, and use version control systems for tracking changes.

Dive deeper with BotPenguin

Surprise botpenguin has fun blogs too.

We know you’d love reading them, enjoy and learn.

11 Best AI Affiliate Programs to Boost Your Earnings in 2024

BotPenguin AI Chatbot Maker

Discover the 20 Best High Ticket Affiliate Programs for 2024

BotPenguin AI Chatbot Maker

The Top 10 Use Cases of MosaicML MPT LLM Model

BotPenguin AI Chatbot Maker

Manish Goyal

Ready to see BotPenguin in action?

BotPenguin AI Chatbot Maker

BotPenguin is the best AI Chatbot maker platform. Create a Chatbot for WhatsApp, Website, Facebook Messenger, Telegram, WordPress & Shopify with BotPenguin - 100% FREE! Our chatbot creator helps with lead generation, appointment booking, customer support, marketing automation, WhatsApp & Facebook Automation for businesses. AI-powered No-Code chatbot maker with live chat plugin & ChatGPT integration.

Get it on apple store

Integrations

  • ChatGPT Popular
  • GoHighLevel New
  • SimplyBook New
  • Google Calendar
  • Google Sheets
  • All Integrations
  • Microsoft Teams New
  • Instagram New

Get started

  • Chatbot For Ecommerce
  • Chatbot For Real Estate
  • Chatbot For Travel
  • Chatbot For Education
  • All Templates
  • WhatsApp Link Generator
  • WhatsApp QR Code Generator
  • OpenAI API Pricing Calculator
  • Chatbot ROI Calculator
  • All Free Tools
  • Whatsapp Whitelabel Partner
  • Whitelabel Partner
  • Affiliate Partner
  • Implementation Partner

Resources/Learn

  • Help Center
  • Write for us

Comparisons

  • BotPenguin vs Manychat
  • BotPenguin vs Tidio
  • BotPenguin vs Tawk to
  • BotPenguin vs Wati
  • BotPenguin vs Interakt
  • BotPenguin vs AiSensy
  • BotPenguin vs Landbot
  • All Comparisons
  • Alternatives

What you get

  • Lead Generation Bot
  • Support Bot
  • Assistant Bot
  • Terms & Conditions
  • Privacy Policy
  • Refund Policy

Copyright © 2018 - 2024 Relinns Technologies Pvt. Ltd. All Rights Reserved.

Integration

Copyright © 2018 - 2024 Relinns Technologies Pvt. Ltd.All RightsReserved.

Let's get in touch

Fill up the form and our team will get back to you within 24 hours

BotPenguin logo

[email protected]

BotPenguin AI Chatbot Maker

By submitting this form you agree to our terms. View our privacy policy to learn about how we use your information.

close

Coding Help Tips Resources Tutorials

Google Apps Scripts and Web Development Tutorials and Resources by Laurence Svekis

Mastering Google Apps Script: A Comprehensive Guide

Are you looking to supercharge your productivity and automate repetitive tasks within Google Workspace? Look no further than Google Apps Script! In this comprehensive guide, we’ll explore everything you need to know about Google Apps Script, from its basics to advanced features.

What is Google Apps Script?

Google Apps Script is a powerful cloud-based scripting language developed by Google. It allows users to extend the functionality of various Google Workspace applications, such as Google Docs, Sheets, Slides, Forms, and Gmail, by writing custom scripts.

Which Google Workspace apps does Google Apps Script support?

Google Apps Script supports integration with a wide range of Google Workspace apps, including:

  • Google Docs
  • Google Sheets
  • Google Slides
  • Google Forms
  • Google Drive
  • Google Calendar
  • Google Sites
  • Google Maps
  • Google Analytics
  • Google BigQuery

Primary language used in Google Apps Script

The primary language used in Google Apps Script is JavaScript, a popular and versatile programming language widely used for web development.

Features of Google Apps Script

Google Apps Script offers a plethora of features, including:

  • Custom function creation
  • Automation of repetitive tasks
  • Integration with external APIs
  • Email sending capabilities
  • User interface creation
  • Data manipulation and processing
  • Access to Google Workspace services
  • And much more!

Google Apps Script Editor

The Google Apps Script Editor is a web-based integrated development environment (IDE) provided by Google. It allows users to write, edit, and debug their scripts directly within the browser.

Accessing Google Apps Script Editor

To access the Google Apps Script Editor:

  • Open a Google Workspace app, such as Google Docs or Sheets.
  • Go to Extensions -> Apps Script .

Running Google Apps Script functions

Google Apps Script functions can be run directly from within the Google Apps Script Editor or by creating custom triggers. Triggers allow functions to be executed based on specific events or schedules.

Triggers in Google Apps Script

Triggers in Google Apps Script are special functions that are executed automatically based on predefined conditions or schedules. They can be set up to run functions at specific times, such as on form submission or at regular intervals.

Interacting with Google Drive

The DriveApp service in Google Apps Script allows users to interact with Google Drive files and folders programmatically. It provides methods for creating, accessing, modifying, and deleting files and folders within Google Drive.

Maximum execution time

The maximum execution time for a single execution of a Google Apps Script function is 6 minutes. If a function exceeds this time limit, it will be terminated automatically.

Sending emails programmatically

The GmailApp service in Google Apps Script allows users to send emails programmatically. It provides methods for composing and sending emails, as well as for managing email drafts and threads.

Deploying Google Apps Script projects

Google Apps Script projects can be deployed for use by others by publishing them as web apps or as Google Workspace add-ons. Web apps can be accessed via a unique URL, while add-ons can be installed directly from the Google Workspace Marketplace.

Authentication methods

To secure Google Apps Script projects that access sensitive user data, it is recommended to use OAuth 2.0 authentication. OAuth 2.0 allows users to grant access to their Google account data without sharing their passwords.

Scripting language

The scripting language used in Google Apps Script for creating custom functions and automation is JavaScript. JavaScript is a versatile programming language widely used for web development and scripting.

Accessing external APIs

Google Apps Script allows users to access external APIs using various methods, such as the UrlFetchApp service. This service enables users to make HTTP requests to external endpoints and retrieve data in JSON or XML format.

Utilities service

The Utilities service in Google Apps Script provides various utility functions for common tasks, such as encoding and decoding data, formatting dates and times, generating unique identifiers, and more.

Custom menu items

The SpreadsheetApp and DocumentApp services in Google Apps Script allow users to create custom menu items in Google Sheets and Google Docs, respectively. These menu items can be used to trigger custom functions or scripts.

Lock Service

The LockService in Google Apps Script allows users to create and manage locks, which prevent concurrent access to shared resources. Locks can be used to synchronize access to critical sections of code and prevent data corruption.

Retrieving data from external APIs

To retrieve data from external APIs in Google Apps Script, users can use the UrlFetchApp service to make HTTP requests to the API endpoints. Once the data is retrieved, it can be parsed and processed as needed.

CORS in Google Apps Script

CORS stands for Cross-Origin Resource Sharing, a security feature implemented by web browsers to restrict access to resources from different origins. In the context of Google Apps Script and web development, CORS may need to be configured to allow requests to external APIs.

Scheduling function execution

The ScriptApp service in Google Apps Script allows users to schedule the execution of functions at specific intervals using triggers. This enables users to automate tasks and processes that need to run periodically.

Spreadsheet service

The SpreadsheetApp service in Google Apps Script allows users to interact with Google Sheets programmatically. It provides methods for creating, accessing, and modifying spreadsheet data, as well as for formatting and styling sheets.

Maximum file size

The maximum file size that can be processed by Google Apps Script when accessing files in Google Drive depends on the specific API being used. However, as a general rule, file sizes should be kept within reasonable limits to ensure efficient processing.

Logging messages

The Logger in Google Apps Script allows users to log messages for debugging purposes. Messages logged using the Logger are stored in a built-in logging console and can be viewed from the Google Apps Script Editor.

Card service

The CardService in Google Apps Script allows users to create interactive cards for Google Workspace applications, such as Google Sheets, Google Docs, and Gmail. These cards can contain interactive UI elements, such as buttons, checkboxes, and text inputs.

Google Apps Script is a powerful tool that allows users to extend the functionality of Google Workspace applications and automate repetitive tasks. By leveraging its features and capabilities, users can streamline their workflows, increase productivity, and unlock new possibilities for collaboration and innovation.

Whether you’re a beginner or an experienced developer, mastering Google Apps Script opens up a world of possibilities for customization and automation within Google Workspace. So why wait? Start exploring the possibilities today and take your productivity to the next level with Google Apps Script!

Stay tuned for more tips, tricks, and tutorials on mastering Google Apps Script and maximizing your productivity in Google Workspace!

25 Apps Script Quiz Questions

a) A programming language for creating web applications b) A scripting language for automating tasks in Google Apps c) A tool for designing graphics in Google Sheets d) A feature for managing emails in Gmail Answer: b) A scripting language for automating tasks in Google Apps Explanation: Google Apps Script is a JavaScript-based scripting language that enables you to automate tasks across Google products and third-party services. It allows users to extend the functionality of Google Workspace apps like Google Sheets, Docs, and Gmail, by writing code to automate processes and workflows.

Which of the following Google Workspace apps does Google Apps Script support?

a) Google Drive b) Google Calendar c) Google Slides d) All of the above Answer: d) All of the above Explanation: Google Apps Script supports integration with various Google Workspace apps, including Google Drive, Calendar, Slides, Sheets, Docs, Forms, and Gmail, among others. This allows developers to create custom functions, automate tasks, and extend the functionality of these apps using scripts.

What is the primary language used in Google Apps Script?

a) Python b) JavaScript c) Ruby d) Java Answer: b) JavaScript Explanation: Google Apps Script is based on JavaScript, a widely-used programming language for web development. Developers write scripts in JavaScript to interact with Google services, manipulate data, and automate tasks within Google Workspace apps.

Which of the following is NOT a feature of Google Apps Script?

a) Creating custom functions in Google Sheets b) Sending automated emails with Gmail c) Editing images in Google Photos d) Integrating with external APIs Answer: c) Editing images in Google Photos Explanation: While Google Apps Script allows users to interact with various Google services and external APIs, direct editing of images in Google Photos is not a feature. However, it can be used to automate tasks related to managing images stored in Google Drive.

What is the Google Apps Script editor?

a) A text editor for writing scripts b) A visual editor for designing user interfaces c) A spreadsheet editor for creating custom functions d) A photo editor for editing images Answer: a) A text editor for writing scripts Explanation: The Google Apps Script editor is a web-based integrated development environment (IDE) where developers write, edit, and debug scripts. It provides syntax highlighting, auto-completion, and debugging tools to aid in script development.

How do you access Google Apps Script Editor?

a) From the Chrome Web Store b) Through the Google Workspace Admin Console c) Within Google Sheets, under the “Extensions” menu d) By selecting “Apps Script” from the “More” menu in Google Drive Answer: d) By selecting “Apps Script” from the “More” menu in Google Drive Explanation: You can access the Google Apps Script Editor by navigating to Google Drive, clicking on the “More” menu (three vertical dots), and selecting “Apps Script” from the dropdown menu.

Which Google Workspace app allows you to run Google Apps Script functions?

a) Google Sheets b) Google Calendar c) Google Slides d) Google Sites Answer: a) Google Sheets Explanation: Google Sheets allows users to run custom functions created using Google Apps Script. These functions can be invoked from the Sheets menu or through custom triggers.

What is a trigger in Google Apps Script?

a) A function that triggers the execution of another function b) A time-based or event-based mechanism that initiates the execution of a script c) A user interface element for interacting with scripts d) A security feature that restricts access to certain script functions Answer: b) A time-based or event-based mechanism that initiates the execution of a script Explanation: Triggers in Google Apps Script are special functions that can be set to run automatically based on specific events or time intervals, such as opening a document, submitting a form, or at a scheduled time.

Which service is used to interact with Google Drive files and folders in Google Apps Script?

a) DriveApp b) FileService c) DriveAPI d) GDrive Answer: a) DriveApp Explanation: The DriveApp service in Google Apps Script allows developers to access and manipulate files and folders stored in Google Drive programmatically.

What is the maximum execution time for a single execution of a Google Apps Script?

a) 1 minute b) 5 minutes c) 10 minutes d) 30 minutes Answer: c) 10 minutes Explanation: The maximum execution time for a single execution of a Google Apps Script is 10 minutes. If a script exceeds this limit, it will be terminated automatically.

Which Google Apps Script service allows you to send emails programmatically?

a) GmailService b) EmailApp c) MailAPI d) Mailer Answer: b) EmailApp Explanation: The EmailApp service in Google Apps Script allows developers to send emails programmatically from Gmail accounts associated with Google Workspace.

How do you deploy a Google Apps Script project for use by others?

a) Share the script file directly with other users b) Publish it as a web app c) Embed it into a Google Sites page d) Export it as a standalone executable file Answer: b) Publish it as a web app Explanation: You can deploy a Google Apps Script project for use by others by publishing it as a web app. This generates a URL that can be shared with users to access the functionality provided by the script.

Which of the following authentication methods is recommended for securing Google Apps Script projects that access sensitive user data?

a) Basic authentication b) OAuth 2.0 c) API key d) No authentication is necessary Answer: b) OAuth 2.0 Explanation: OAuth 2.0 is the recommended authentication method for securing Google Apps Script projects that access sensitive user data. It allows users to grant permission to third-party applications to access their Google account without sharing their password.

What is the scripting language used in Google Apps Script for creating custom functions and automation?

a) Python b) Java c) JavaScript d) Ruby Answer: c) JavaScript Explanation: Google Apps Script uses JavaScript as its scripting language for creating custom functions, automating tasks, and extending the functionality of Google Workspace apps.

How can you access external APIs from within Google Apps Script?

a) By importing API libraries directly into the script b) By using the built-in Fetch service c) By requesting API access from Google Workspace Admin Console d) By enabling API access in Google Cloud Platform Console Answer: b) By using the built-in Fetch service Explanation: Google Apps Script provides a built-in Fetch service that allows developers to make HTTP requests to external APIs, enabling interaction with a wide range of third-party services and data sources.

What is the purpose of the Utilities service in Google Apps Script?

a) To manage user authentication b) To access and manipulate spreadsheet data c) To work with dates, strings, and other utility functions d) To send and receive emails Answer: c) To work with dates, strings, and other utility functions Explanation: The Utilities service in Google Apps Script provides various utility functions for working with strings, dates, and other miscellaneous tasks like base64 encoding and formatting.

Which Google Apps Script method is used to create custom menu items in Google Sheets or Google Docs?

a) createMenu() b) addMenu() c) setMenu() d) insertMenu() Answer: a) createMenu() Explanation: The createMenu() method in Google Apps Script is used to create custom menu items in Google Sheets or Google Docs. These custom menus allow users to access scripts and functions directly from the interface.

What is the purpose of the Lock Service in Google Apps Script?

a) To secure sensitive data stored in Google Drive b) To prevent concurrent access to shared resources c) To restrict access to certain script functions based on user roles d) To encrypt communications between Google services and external APIs Answer: b) To prevent concurrent access to shared resources Explanation: The Lock Service in Google Apps Script is used to prevent multiple simultaneous executions of a section of code, ensuring that shared resources are accessed safely and consistently.

Which Google Apps Script method is used to retrieve data from an external API?

a) fetchData() b) fetchUrl() c) UrlFetchApp.fetch() d) retrieveData() Answer: c) UrlFetchApp.fetch() Explanation: The UrlFetchApp.fetch() method in Google Apps Script is used to make HTTP requests to external APIs, allowing developers to retrieve data and interact with third-party services.

What does CORS stand for in the context of Google Apps Script and web development?

a) Cross-Origin Resource Sharing b) Centralized Object Relational System c) Combined Operations and Resource Sharing d) Cross-Platform Object Resolution Service Answer: a) Cross-Origin Resource Sharing Explanation: CORS (Cross-Origin Resource Sharing) is a mechanism that allows web pages to request resources from another domain, enabling secure cross-origin data transfers between different origins in web applications.

Which Google Apps Script method is used to schedule the execution of a function at specific intervals?

a) setInterval() b) triggerEvent() c) setTimer() d) addTrigger() Answer: d) addTrigger() Explanation: The addTrigger() method in Google Apps Script is used to schedule the execution of a function at specific intervals or based on specific events, such as time-based triggers or triggers from external sources like Google Forms.

What is the purpose of the Spreadsheet service in Google Apps Script?

a) To create and manipulate Google Sheets files b) To generate and send emails from Google Sheets c) To import and export data between Google Sheets and external databases d) To provide real-time collaboration features in Google Sheets Answer: a) To create and manipulate Google Sheets files Explanation: The Spreadsheet service in Google Apps Script provides methods for creating, accessing, and manipulating Google Sheets files programmatically, allowing developers to automate tasks and workflows involving spreadsheet data.

What is the maximum file size that can be processed by Google Apps Script when accessing files in Google Drive?

a) 5 MB b) 10 MB c) 25 MB d) 50 MB Answer: c) 25 MB Explanation: The maximum file size that can be processed by Google Apps Script when accessing files in Google Drive is 25 MB. Files larger than this limit may encounter issues during processing.

Which Google Apps Script method is used to log messages to the built-in Apps Script Logger?

a) logMessage() b) console.log() c) Logger.log() d) debug() Answer: c) Logger.log() Explanation: The Logger.log() method in Google Apps Script is used to log messages to the built-in Apps Script Logger, which can be accessed from the Apps Script editor. This is helpful for debugging and monitoring script execution.

What is the purpose of the Card service in Google Apps Script?

a) To create custom UI elements for Google Workspace add-ons b) To manage user authentication and authorization c) To generate QR codes for embedding in Google Docs d) To create interactive charts and graphs in Google Sheets Answer: a) To create custom UI elements for Google Workspace add-ons Explanation: The Card service in Google Apps Script allows developers to create custom user interface elements, such as cards, dialogs, and sidebars, for use in Google Workspace add-ons and extensions.

Share this:

Alem Tuzlak's blog

Deep dive into package.json scripts

Photo by Cristian Palmer on Unsplash

Deep dive into package.json scripts

How do package.json scripts work & everything you need to know on how to get you started.

Alem Tuzlak's photo

23 min read

Table of contents

How does npm work, external scripts, internal scripts, pre scripts, post scripts, lifecycle scripts.

If you've ever worked on a project that includes any sort of Javascript chances are there is a package.json included in the project. This package.json file is a very intimidating one when starting out and you're very scared to touch it in the fear you will break something.

This article is the first in a series of deep dives into package.json fields, how they work, what they do and how you can use them to your advantage and make your project even better, make you feel comfortable to play around with package.json fields, allow you to create a CLI and more!

This article covers the "scripts" section and by the end, you will understand how to write your very own scripts in JS & TS (both CJS & ESM).

So without further ado let's dive right into the scripts part of our good old friend package.json!

Before we get into the package.json part let's go over how npm works and executes scripts for you.

When you install node to your PC it installs npm (node package manager) & npx for you too. It adds them to your PATH and allows your PC to execute npm as an executable. It comes with a bunch of built-in commands such as:

run - allows you to run scripts

pack - packs a tarball of your project (useful for OSS)

publish - publishes your package to NPM registry (useful for OSS)

dependencies - runs after any sort of change to node_modules directory

ci - allows you to cleanly install dependencies by clearing the node_modules and then running npm install

install - installs your package.json dependencies and devDependencies into the node_modules directory

uninstall - removes a depedency/devDependency from your project

And a bunch more commands, if you're interested in the whole list and want to go deeper you can find the documentation document on the following link:

https://docs.npmjs.com/cli/v10/commands

After this, you can use it to execute scripts via npm run <script-name> where the script-name matches a script in your package.json file.

If you want to add global executables you can by installing a package as a global dependency, for example, if you want a package that injects .env variables available globally you can run:

This will add it to your global npm dependencies so if you try to execute dotenv anywhere on your pc it will work, or if you have a script in your package.json like so:

It will work because you have it installed globally, but in many cases, this is not needed, for example, if you do not want to install it globally you can add this dependency to your package.json under devDependencies and npm is smart enough to first look into your node_modules for the executable, if it is not there it will then look globally, so by having this in your package.json:

And lastly, another trick you can use is to use npx. It will install the executable before running the command like so:

But this shouldn't be done in most cases because you can get version mismatches and other issues! Just because it worked a month ago you are not guaranteed that it will work today if the versions change.

If you're wondering what the && is for it allows us to run multiple scripts one after another, if you wish to add a script that runs multiple scripts in parallel there is a great package that you can look at for this use-case:

https://www.npmjs.com/package/npm-run-all

One last thing before we transition to scripts is understanding how flags and parameters work in npm.

If you have seen something like npm run test -- --watch you probably wondered what is going on here. Well, in short, you can pass parameters to any script and there are two main ways of doing this.

The first one is that you add a special -- delimiter that tells npm that it should pass everything that comes after it to the script that is being run, so from our case above, if our script is something like:

Assuming our test script is for example:

This will result in the --watch flag being passed down to the script and the final script that is going to be run is:

Another way to pass parameters is by passing them WITHOUT the trailing - or -- , for example:

this will result in the command:

So the main two ways to pass parameters are either by adding -- before the parameters which is explicitly telling npm to pass them along or by excluding the prefixes entirely.

Here is a list of commands and what they result in for your better understanding:

If you want to understand this even more you can look at this SO issue that explains it in detail and adds additional links for more investigation: https://stackoverflow.com/questions/11580961/sending-command-line-arguments-to-npm-script

Types of scripts

So before we go too deep into scripts and what they can and how they work let's first understand the types of scripts there are! I will classify all scripts into two types; external and internal scripts.

Under external scripts, I will group everything that is executed by a third-party package and not by your hand-made scripts. These will probably make the majority of your package.json scripts because a lot of scripts rely on third-party packages like Jest, Prisma, Vitest etc.

There are also special kinds of scripts run with npx that fall into this category. If you're not aware npx allows you to execute any script (not just ones from npm) without having to install the script, so what you can do with npx is:

Run github gists/scripts

Run npm packages without installing dependencies (eg. running npx prisma commands in your build pipeline without having it in your dependencies)

Run local scripts that are located in your $PATH variable

Another cool thing about npx is that it installs the dependencies of the script temporarily and executes them instead of keeping them around.

It also comes bundled with npm and is the de facto standard of running external scripts that you do not want to have locally installed

These scripts are external and are usually bundled as executables on npm, but as I mentioned above, they are not limited to npm due to the fact you can run scripts from anywhere using npx

Now these are the in-house scripts that you create for yourself to make your life easier and boost your productivity. These can include anything from generating code snippets, injecting code, checking the validity of some entities, generating icons, optimizing images and the list goes on!

These scripts are usually located in the project directory itself and are bound to the current project as they are context-specific, eg. if you're generating icons from an input file located in /public to somewhere in your app, eg. /app/icons then this might not be a useful script in another project because that project doesn't have the /public or app/icons directories.

Towards the end of the article we will be building our own setup script!

Script keywords

Now that we went over the two kinds of scripts let's go over some special script keywords you need to be aware of!

These are special scripts that start with the pre keyword in the package.json scripts, eg:

These scripts are meant to be executed BEFORE the script you specify after the pre keyword, you can add this to any script in your package.json and it will execute before the script.

If you have a db:seed:prod script and want to do a check before you seed you can add a predb:seed:prod script to execute something before the actual script executes.

The important thing to note is that you can run anything before another script by just specifying pre<script-name> and it will be executed before.

The idea is pretty much the same as the pre scripts but these scripts execute AFTER the script has run, usually these scripts are used for cleanup or validation, eg:

As you can see the approach is the same as the pre script, the only difference is that you add post<script-name> instead of the pre keyword

As I mentioned above npm comes with a lot of installed commands by default, there are special lifecycle scripts that are executed in certain conditions when you run one of these npm commands such as:

prepare - Runs BEFORE the package is packed, i.e. during npm publish and npm pack

prepublish - Does not run during npm publish , but does run during npm ci and npm install . This command is deprecated for prepublishOnly and you should use that one instead though!

prepublishOnly - Runs BEFORE the package is prepared and packed, ONLY on npm publish .

prepack - Runs BEFORE a tarball is packed

postpack - Runs AFTER the tarball has been generated but before it is moved to its final destination

dependencies - Runs AFTER any operations that modify the node_modules directory IF changes occurred.

Detailed info on all of these can be found here: https://docs.npmjs.com/cli/v10/using-npm/scripts#life-cycle-scripts

These scripts are not that useful if you're not building a OSS project as they are mostly used in those scenarios but they can have their use cases in normal projects as well!

Writing custom scripts

Alright so now that we have a firm grasp of how scripts work let us explore how we can write our scripts to do some cool stuff. I will be writing both a js/ts version in this guide so you can fully understand what the differences are and what you need to do in each scenario.

In this section, I will write a script that does the following things:

Takes in an environment argument and loads the correct .env file so you can run scripts in whatever .env you wish.

Add a confirm prompt so you have to confirm you want to run a script before you execute it

What this script basically does is that it allows you to set up the .env for another script before it is executed! Let's start with the common setup first.

The first thing we want to do is create a repository with a package.json file. You can create an empty directory on your PC and then inside it run npm init and go through the setup, whatever you select doesn't really matter.

After we have this we create a /scripts directory on the root of the newly created application, so if you call it something like test-app the path should be test-app/scripts .

Now depending on if you're going to follow in JS or TS create either a setup.js or a setup.ts file inside of the /scripts directory. Also, create a test.js or test.ts in the /scripts as well.

For the testing of these commands let's add .env and .env.prod

After that I want you to run the following inside your app:

This will install the devDependencies we need, the -D flag is a shortcut for --save-dev . Chalk went to native ESM bundling from version 5 so if you're using CJS you need to install a version before 5, so we installed version 4 for this.

This is optional if you don't want to make your output prettier you don't have to add chalk! It just adds colors to the console output.

Dotenv is a popular package that we will use to inject the .env into our process and prompt is a simple library used to prompt the user with a question in the terminal.

Now you can paste the following script into the file and then we can go over what exactly it does:

Let's go one step at a time and explain each part of the script. The first thing you need to keep in mind is that script execution goes from top to bottom and executes all the code inside of the file it can execute, so if you want to execute code you either keep it on the top level of your file or if you want to conditionally execute something you wrap it in a method and then call that method.

The first part of the code is simple enough, we just define an environment constant that holds all our possible environments, you can extend this to your liking:

After that, we have our get environment utility that we use in our other functions to get some info we need:

We first extract the env argument from the script by trying to find it in the process.argv (this will hold all your arguments you pass to the script, the first two places are reserved but it is an array of arguments passed in essentially).

If you want to learn more about node process and how it works and the APIs it exposes you can find the documentation here: https://nodejs.org/api/process.html

If we find it we create the env name so we don't console log undefined or empty string and then we define the path to the env, eg if the argument is "stage" that will set the path to .env.stage , this part you can change to whatever your configuration is.

Then after that, we have the confirmRun function that we use at the bottom of the script conditionally to either prompt the user that he is sure he wants to run the script and it either exits the script or continues the execution.

Finally, for the last of our helper methods, we have the setupEnv utility that runs right after its declaration to inject the .env file contents into the process and this is done using dotenv .

So the next few lines of code are interesting, mainly I am talking about this piece of code:

As I already mentioned, npm puts all your parameters into argv and here we check if the user has provided any parameter, if not we early exit and tell him to do so. If you try running the script and do not provide what to execute it will fail and exit early.

Right after that, we call the setupEnv() to inject the .env file for our script, this is where the part about running everything in your js file I mentioned above comes in, as soon as Node reaches this part it will call the setupEnv function and execute its content.

Finally, we reach the meat of our execution, the main function. Let's go piece by piece and explain what is going on.

So as I said earlier process.argv fills in the first 2 positions with information already, and we have a guard if the 3rd argument is missing, so we check if the argument starts with scripts/ and if it does we set the command to be npm run execute <command> otherwise it will just be the command passed in. This allows us to do the following:

But this is also flexible and allows us to inject .env files into our third-party scripts, for example, if we wanted to inject .env.stage into vitest we could run:

or maybe we want to use different Prisma databases to see our DB data, we could run

Now that we have that covered, we want to strip away any arguments that we passed into our setup script, we do this by doing the following:

Because the first 2 spots are filled by node, and the 3rd is our command, we remove those. We also removed "confirm" and "<env>" arguments if we passed them in, and everything else that was left we passed into the underlying script.

For the following code snippet, I won't go into too much detail on how the underlying API works because it's out of the scope of this exercise but it basically spawns a child process on our current process and inherits its console output, sets the directory location to the current working directory (project root) and passes in the command and arguments we prepared from above. Then it adds listeners to exit events for the process and child process to make sure that you gracefully exit and close everything if you terminate the process or it fails:

Last, but not least, we run our main command, but with a catch! If we add the confirm argument to our parameters it will first prompt us to confirm that we want to continue (this is useful if you don't want to accidentally run a script that kills your production DB), if it's not present it will continue and execute the command normally without the prompt:

Alright, we covered everything! Now one last thing before we move onto the js/ts implementations, add this to your package.json:

Alright, let's get to work! First the easy one, Javascript!

Assuming you've done the setup above paste the following commands into your package.json :

And add this to your test.js :

So what are we doing here?

Well first we define a execute a script that will be what executes and runs our scripts, in our case it's node, but we will see below it can be something different in the TS example.

Then we add the script utility that will run our setup.ts inside of the /scripts directory that we created earlier, inject our environment variables and ask us to confirm if needed.

After these two are added we can start writing our new scripts that will actually do something on top of this, the scripts I wrote are just to show what will happen so if I run:

You will get the following output:

writing custom scripts

And if you run:

writing custom scripts

Awesome! We are injecting our env into our scripts! But what if we want to confirm the action before we run the script? Well, that's what confirm parameter is for!

If you run the confirm script like so:

You get the following prompt:

writing custom scripts

If you say no:

writing custom scripts

And if you say yes:

writing custom scripts

Awesome! There we have it, a completely working setup script! Now let's see how we get this running with typescript

So for Typescript, there are a few caveats that you need to understand before we actually jump into the implementation of it. Typescript can't run your code until it's compiled into Javascript, this means that you need to first run it through a process of compilation to get it in JS format to be able to execute it. There are two flavors of TS outputs, CJS and ESM. This article doesn't go into depth about these two topics but you can find an amazing article about it here (written by the one and only Anthony Fu):

https://antfu.me/posts/publish-esm-and-cjs

For the compilation we will be using ts-node, you can find their docs on their GitHub or npm and detailed instructions on how to use it. I will cover both the CJS/ESM variants below. So without further ado let's jump into the TS implementation!

The flow is identical to the Javascript one but there are a few extra steps you need to follow to get it working, all of these are listed below.

Firstly install TS:

This will install TS as a dev dependency and initialize a tsconfig.json file for you.

If you want to run the scripts with ESM you can add the following to your tsconfig.json :

And you will need to install the latest version of chalk (5.0.0 or higher).

Then you add the following to your package.json :

And you're good to go! Don't also forget to replace any ".js" extension in your scripts with ".ts".

If you want to run it in a CJS environment you will need the following tsconfig.json

You will need to remove the following from package.json :

Install chalk version 4 (version 5 is ESM only), you can do so by running:

And finally, add the following to your package.json :

And we are good to go! We have our scripts working in both CJS & ESM flavors!

If you've made it here you are a real champ! Thank you for sticking through the whole article and going on a deep dive into package.json scripts with me. If you like my content and want to learn more this is the first in a series of articles I plan to write on the deep dive into package.json so be sure to follow me for more!

If you wish to support me follow me on Twitter here:

twitter.com/AlemTuzlak59192

or if you want to follow my work you can do so on GitHub:

github.com/AlemTuzlak

And you can also sign up for the newsletter to get notified whenever I publish something new!

Google Sheet Script Editor: How to Master It in Simple Steps

Using the Google Sheet Script Editor might seem like a daunting task, but it’s actually quite simple. All you need to do is access the editor, write your script, and then run it to automate tasks within your spreadsheet. It’s a powerful tool that can save you time and streamline your workflow.

Step by Step Tutorial: How to Use the Google Sheet Script Editor

Before diving into the steps, let’s understand what we’re aiming to achieve. The Google Sheet Script Editor allows you to write custom scripts, or small programs, that can interact with your Google Sheets. These scripts can automate tasks, analyze data, and much more.

Step 1: Open the Script Editor

Open your Google Sheet and click on “Extensions” in the menu, then select “Apps Script.”

When you open the Script Editor for the first time, you’ll see a blank project. This is where you’ll write your code. The editor is based on JavaScript, so if you’re already familiar with that language, you’re one step ahead.

Step 2: Write Your Script

In the Script Editor, type your code into the blank space.

You can write a script that does just about anything you can imagine. From sending emails based on spreadsheet data to formatting cells automatically, the possibilities are endless. If you’re new to coding, there are plenty of tutorials and resources available online to help you get started.

Step 3: Save Your Script

Click the disk icon or go to “File” and select “Save” to save your script.

Always remember to save your work regularly. There’s nothing worse than writing a brilliant piece of code and then losing it because you forgot to save.

Step 4: Run Your Script

Click the play button located at the top of the screen to run your script.

After running your script, you’ll see the results in your Google Sheet. If your script is meant to send emails, for example, those emails will be sent when you run the script. If you encounter any errors, the Script Editor will provide error messages to help you troubleshoot.

Step 5: Debug Your Script

If your script isn’t working as expected, use the debugging tools provided in the Script Editor to fix any issues.

Debugging can be tricky, but the Script Editor provides a debugger that allows you to step through your code one line at a time. This can help you find and fix any errors or bugs.

After completing these steps, your custom script will be up and running, performing tasks automatically within your Google Sheet.

Tips for Using the Google Sheet Script Editor

  • Start with simple scripts and gradually work your way up to more complex ones.
  • Utilize the “Record macro” feature to record actions you take in Google Sheets and generate a script.
  • Make use of the extensive Google Apps Script documentation for guidance and inspiration.
  • Always test your scripts on a copy of your spreadsheet to avoid any unwanted changes.
  • Join online communities or forums to learn from other Google Sheets power users and scriptwriters.

Frequently Asked Questions

What is google apps script.

Google Apps Script is a cloud-based scripting language for light-weight application development in the G Suite platform.

Can I use Google Sheet Script Editor without any coding experience?

Yes, you can! There are plenty of resources and tutorials available that can help beginners learn how to write basic scripts.

Is it possible to share scripts with others?

Yes, you can share your scripts by sharing the Google Sheet or by making the script itself available online.

Can scripts run automatically at a scheduled time?

Yes, you can use time-driven triggers to run your scripts at scheduled intervals.

Are there any limitations to what I can do with scripts in Google Sheets?

While Google Apps Script is powerful, it does have certain limitations, such as execution time limits and API call quotas.

  • Open the Script Editor from the Extensions menu
  • Write your custom script in the editor
  • Save your script regularly
  • Run your script to see it in action
  • Debug any issues if your script isn’t working properly

The Google Sheet Script Editor is a versatile tool that can take your spreadsheet game to the next level. Whether you’re looking to automate repetitive tasks, analyze complex data sets, or simply save time, learning how to use the script editor can be incredibly rewarding. Remember, like any new skill, it may take some time to get the hang of it. But with a bit of practice and patience, you’ll be writing custom scripts like a pro. The key is to start simple, use the resources available, and don’t be afraid to ask for help. So go ahead, dive in, and unlock the full potential of Google Sheets with the power of scripting.

Matthew Burleigh Solve Your Tech

Matthew Burleigh has been writing tech tutorials since 2008. His writing has appeared on dozens of different websites and been read over 50 million times.

After receiving his Bachelor’s and Master’s degrees in Computer Science he spent several years working in IT management for small businesses. However, he now works full time writing content online and creating websites.

His main writing topics include iPhones, Microsoft Office, Google Apps, Android, and Photoshop, but he has also written about many other tech topics as well.

Read his full bio here.

Share this:

Join our free newsletter.

Featured guides and deals

You may opt out at any time. Read our Privacy Policy

Related posts:

  • How to Create a MS Excel Script: A Step-by-Step Guide
  • How to Insert Scripts Into PowerPoint: A Step-by-Step Guide
  • How to Download a Google Sheet as an Excel File
  • What is the Best Microsoft Word Cursive Font?
  • How to Use Script Formatting in Google Docs: A Step-by-Step Guide
  • How to Wrap Text in Google Sheets
  • How to Create a New Google Sheets Spreadsheet in Google Drive
  • How to Make a Header Row in Google Sheets
  • How to Add a Title in Google Sheets
  • How to Turn Off Google Sheets Autocomplete
  • How to Indent Text in Google Sheets
  • How to Save as a CSV from Google Sheets
  • How to Make All Columns the Same Width in Excel 2013
  • How to Use Google Sheets: A Comprehensive Guide for Beginners
  • How to Alphabetize on Google Sheets
  • Google Sheets: How to Reference Another Sheet for Seamless Data Management
  • How to Insert a Graph in Google Docs
  • How to Remove Google Sheets Notes
  • How to Embed Google Sheets in WordPress
  • How to Convert a Google Sheets File to a PDF

SmartScripter is an AI-driven web application designed for script generation in multiple programming languages

Describe what you want the vba script to do:, free account, premium plan.

Industries Thriving With Smart Scripter

Transform Your Workflow.

SmartScripter is your go-to solution for automating tasks like spreadsheet management, administrative duties, web development projects, command line tasks, and data analysis processes. By simplifying these tasks, SmartScripter empowers you to concentrate on higher-level activities and make well-informed decisions.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Allow or prevent custom script

  • 26 contributors

As a Global Administrator or SharePoint Administrator in Microsoft 365, you can allow custom script as a way of letting users change the look, feel, and behavior of sites and pages to meet organizational objectives or individual needs. If you allow custom script, all users who have Add and Customize Pages permission to a site or page can add any script they want. (By default, users who create sites are site owners and therefore have this permission.)

For simple ways to change the look and feel of a site, see Change the look of your SharePoint site .

By default, script is not allowed on most sites that admins create using the SharePoint admin center as well as all sites created using the New-SPOSite PowerShell command. Same applies to OneDrive, sites users create themselves, modern team and communication sites, and the root site for your organization. For more info about the security implications of custom script, see Security considerations of allowing custom script .

If SharePoint was set up for your organization before 2015, your custom script settings might still be set to Not Configured even though in the SharePoint admin center they appear to be set to prevent users from running custom script. In this case, users won't be able to copy items between SharePoint sites and between OneDrive and SharePoint. On the Settings page in the SharePoint admin center , to accept the custom script settings as they appear, select OK , and enable cross-site copying. For more info about copying items between OneDrive and SharePoint, see Copy files and folders between OneDrive and SharePoint sites .

To allow custom script on OneDrive or user-created sites

This feature will be removed during H1 calendar year 2024. Once removed, it will no longer be possible to allow custom script on OneDrive sites.

In the SharePoint admin center , you can choose to allow users to run custom script on OneDrive (referred to as personal sites ) or on all classic team sites they create. For info about letting users create their own sites, see Manage site creation in SharePoint .

Before you allow custom script on sites in your organization, make sure you understand the security implications .

Go to Settings in the SharePoint admin center , and sign in with an account that has admin permissions for your organization.

If you have Office 365 operated by 21Vianet (China), sign in to the Microsoft 365 admin center , then browse to the SharePoint admin center and open the Settings page.

At the bottom of the page, select classic settings page .

Under Custom Script , select:

Allow users to run custom script on personal sites .

Allow users to run custom script on self-service created sites .

Screenshot of custom script section of settings page in SharePoint admin center.

Because self-service site creation points to your organization's root site by default, changing the Custom Script setting allows custom script on your organization's root site. For info about changing where sites are created, see Manage site creation in SharePoint .

Select OK . It can take up to 24 hours for the change to take effect.

To allow custom script on other SharePoint sites

To allow custom script on a particular site (previously called site collection ) immediately, follow these steps:

Download the latest SharePoint Online Management Shell .

If you installed a previous version of the SharePoint Online Management Shell, go to Add or remove programs and uninstall SharePoint Online Management Shell .

Connect to SharePoint as a Global Administrator or SharePoint Administrator in Microsoft 365. To learn how, see Getting started with SharePoint Online Management Shell .

Run the following command.

or by means of the PnP.PowerShell cmdlet Set-PnPSite

If you change this setting for a classic team site, it will be overridden by the Custom Script setting in the admin center within 24 hours.

You cannot allow or prevent custom scripts to an individual user's OneDrive.

Manage custom script from SharePoint admin center

If you do not see the new options in SharePoint tenant admin center, the feature is not enabled in your tenant yet. Every customer will have this new set of capabilities enabled by end of June 2024

Tenants administrators have a set of tools available in SharePoint tenant administration to manage custom script within their organization. Specifically, tenant administrators can do the following:

  • verify custom script status
  • change custom script settings
  • persist custom script settings

Verify custom script status

A new Custom script column is now available in the Active sites page under Sites .

Screenshot of active sites view with custom script column visible.

The column can be added to any view. A new Custom script allowed sites is also available to provide an easy access to all the sites where custom script is enabled:

Screenshot of the list of default views, which includes the 'custom script allowed sites' view.

Change custom script settings

In the Active sites page, upon selecting a site, under settings , a Custom scripts setting is available for administrators:

Screenshot of the 'Custom scripts' setting.

Administrators can control custom script settings for a specific site; deciding if they want to allow or block custom script on a specific site:

Screenshot of 'Custom scripts' values.

By default, any changes to custom script settings for a specific site only last for a maximum of 24 hours. After that time, the setting will reset to its original value for that specific site.

Persist custom script settings

To prevent SharePoint in resetting custom script settings to its original value to the whole tenant follow these steps:

If you installed a previous version of the SharePoint Online Management Shell, go to Add or remove programs and uninstall "SharePoint Online Management Shell."

This setting affects all sites. There are no options to preserve changes to custom script settings only on some specific sites. This parameter will be available until November 2024. After that date, it will no longer be possible to prevent SharePoint in resetting custom script settings to its original value for all sites. Running the command where Multi-Geo capabilities on OneDrive and SharePoint are configured, will only affect the current geo from which you ran the command. To persiste custom script settings across the entire tenant you must run the command on each geo.

Features affected when custom script is blocked

When users are prevented from running custom script on OneDrive or the classic team sites they create, site admins and owners won't be able to create new items such as templates, solutions, themes, and help file collections. If you allowed custom script in the past, items that were already created will still work.

The following site settings are unavailable when users are prevented from running custom script:

The following web parts and features are unavailable to site admins and owners when you prevent them from running custom script.

Best practice for communicating script setting changes to users

Before you prevent custom script on sites where you previously allowed it, we recommend communicating the change well in advance so users can understand the impact of it. Otherwise, users who are accustomed to changing themes or adding web parts on their sites will suddenly not be able to and will see the following error message.

Screenshot of the Error message that's displayed when scripting is disabled on a site.

Communicating the change in advance can reduce user frustration and support calls.

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

thumbnail image

Build skills in Unity with guided learning pathways designed to help anyone interested in pursuing a career in gaming and the Real Time 3D Industry.

Explore a topic in-depth through a combination of step-by-step tutorials and projects.

Create a Unity application, with opportunities to mod and experiment.

Find what you’re looking for with short, bite-sized tutorials.

writing custom scripts

Editor Scripting

writing custom scripts

How to write and use custom InDesign scripts

  • Categories:
  • DO MORE with Scripting

This webinar, the second in our DO MORE with Scripting  series  by Peter Kahrel, addresses some practicalities of writing and using custom scripts in Typefi workflows.

You’ll learn about the script development environment (Adobe ExtendScript Toolkit), differences between InDesign Desktop and InDesign Server, interacting with the Typefi Engine, protecting the Typefi Engine’s environment by ringfencing custom scripts, Engine defaults, and testing and deploying scripts.

Welcome to the second webinar on Typefi scripts and scripting. In this session we’ll deal with some practicalities of writing and using scripts in Typefi workflows, including:

  • The script development environment—Adobe’s ExtendScript Toolkit (ESTK);
  • Differences between InDesign Desktop and InDesign Server;
  • How your scripts interact with the Typefi Engine;
  • How to protect the Typefi Engine’s environment by ringfencing your custom scripts;
  • Engine defaults, which you have to know when you write scripts that communicate with the Engine; and
  • Testing and deploying scripts.

This demo uses InDesign CC2018. For scripts this makes no difference—these scripts will work in CC2017 and earlier versions of InDesign.

This webinar is about making you familiar with some relevant parts of the Typefi Engine.

Script development environment (1:32)

This is JavaScript only. InDesign can be scripted with AppleScript and VBasic as well, but these two are platform-specific, so AppleScript works only on Mac and VBasic works only on Windows. On the other hand, JavaScripts can be used on both Mac and Windows platforms—they are platform-independent.

For the script environment, I use Adobe’s ExtendScript Toolkit. It’s a script editor that comes with several development tools, and it can be used for all scriptable Creative Cloud applications. It’s a separate download which is accessible through your Creative Cloud panel.

When you first start the ESTK, it shows various windows. These are useful but take up screen space, so I open them only when I need them. The console, which you see on my screen, I use all the time. The other windows are accessible in the Window menu.

When you start a new script file you first of all need to select the application that you target in this dropdown.

Screenshot showing the ESTK target application menu

The applications that you see here depend on whatever is installed on your computer, so as you can see here I have several versions of InDesign going back to CS6, Photoshop, and a few others.

You must also make sure that the icon next to the target application menu is green, which shows that the ESTK is connected to InDesign.

Screenshot showing the icon next to the ESTK target application menu highlighted green

In the Help menu there is a short, basic Adobe Intro To Scripting . Object Model Viewer we’ll use extensively later (or one of its third-party alternatives). And the JavaScript Tools Guide CC documents the ESTK and its functionality. This is a useful document—it’s very extensive and it has a chapter on the ESTK’s interface.

On Windows PCs, the ESTK works quite well generally, but on Mac there are two problems. The first of the problems is what is referred to as ‘app nap’, which means that sometimes the ESTK takes a nap when you expect it to execute a script, and the editor can be unresponsive from time to time. Unfortunately, there’s not much that you can do about it.

Secondly, Apple has announced that with the next major release of OSX (probably in the summer of this year, 2018), 32-bit applications (like the ESTK) will no longer be supported, which leaves Mac users without a proper development environment. A ludicrous situation, and at the moment (January 2018) it’s not clear what’s going to happen.

For now I’ll deal with the Windows setup, in which the ESTK works pretty well.

InDesign Server vs. InDesign Desktop (5:30)

InDesign scripts that run in InDesign server (as all scripts do when they run as part of an InDesign job on a server), differ in some subtle but important details from those that run in InDesign Desktop—that is, the InDesign version installed on your desktop, and which is used when you installed Typefi Desktop Server.

The main difference between InDesign Desktop and InDesign Server is that InDesign Server doesn’t have an interface—it’s a so-called headless application.

This means that InDesign Server doesn’t use any script property that has ‘active’ in its name (because ID Server has no interface, so the notion ‘active’ doesn’t apply). You may have seen InDesign scripts on a forum or in a printed text that referred to the current document as app.activeDocument , and other comparable property names are activePage and activeWindow . However, these names cannot be used in InDesign Server, but there are equivalent properties: for instance, use app.documents[0] instead of app.activeDocument .

InDesign Server also—naturally—doesn’t know selections: you can’t select anything in InDesign Server, so you have to get access to the document, story, page, etc. in some other way. This will be illustrated later.

There is one script function that’s different in ID Server and ID Desktop, namely, PDF export. Though you would normally use the Typefi Server’s Export to PDF action, it can nevertheless be necessary to export a document by a script or as part of a script. In a script you can determine which InDesign version a script is running in by the application’s name property:

(When run in ID Server, app.name returns ‘Adobe InDesign Server’.)

The difference is in the false parameter. In the Desktop version, this parameter indicates whether InDesign should display the Export Adobe PDF dialogue, but since ID Server has no interface, that parameter is not present in the export function.

The points outlined here pretty much exhaust the differences between the two InDesign versions. They are few, but important.

Protecting the Typefi environment (8:42)

The Typefi Engine is a JavaScript itself and virtually all the scripts you write will interact to some extent with the Typefi Engine. You must therefore ringfence your script to ensure that it does not interfere with the Engine.

The best way to accomplish this is to format your script as a so-called self-executing anonymous function. This mouthful simply means that a script should be wrapped as follows:

This construct works in both Server and Desktop versions of InDesign.

Secondly, and equally importantly, you must ensure that all your variables are confined to your script, which you achieve by declaring them as such:

The first line, in which myPage is declared as a variable, restricts the scope of myPage to the function in which it is defined, in this case, our script (because the script is a function).

The second line, in which myPage is not declared as a variable, broadcasts myPage throughout the script environment, overwriting any existing instances of myPage , even in the Engine. It is therefore crucial that any script you write is wrapped in an anonymous function and that its variables are defined with the reserved word var .

This cannot be stressed enough: make variables local or you run the risk of messing up other scripts, including the Engine.

Typefi Engine defaults (12:17)

The Engine sets some document properties that remain in force throughout the document’s production. Immediately after opening a template, the Typefi Engine sets the document’s rulers to per page and the measurement system to points because these are the most convenient settings to work with. When the job finishes, the original settings are restored in the paginated document.

If you want to use different rulers and/or measurement units you can set them in a script, but you must restore those settings when the script finishes. The Engine sets them only once, at the start of the job, so when a script changes them during pagination, those changed values remain in force.

Thus, if your script changes the units from points to millimetres at page.end , that script must restore the units to points before handing back control to the Engine. If you don’t, the Engine’s measurements go all over the place and you might end up in a very tight place!

Setting measurements and rulers is relatively time-consuming, and you’re advised to change these only when it’s really necessary.

Demo (Part I): Writing a script for a Typefi job (13:19)

Let’s have a look now at the practicalities of writing a script that’s supposed to run in a Typefi job. For our first script we set ourselves a modest task so that we can concentrate on the logistics: we want a script that keeps the last eight characters of every paragraph together to prevent runts—that is, short last paragraph lines. To do this interactively, you’d use a Find/Change operation.

(‘Short’ is of course a matter of taste, and is also determined by the column width, but let’s say that for our purposes, eight characters is the minimum length of a paragraph’s last line.)

When you start writing a script, the first question you ask is at which script event the script should run. Well, since this script doesn’t rely on geometry, and since it can change the text flow, the best moment is at spill.end . Recall that spill.end occurs every time a story story is placed (‘spilled’).

The basic script itself is not too difficult. We’ll use InDesign’s GREP replacement to apply no-break to the last eight characters of every paragraph:

app.findGrepPreferences = app.changeGrepPreferences = null; app.findGrepPreferences.findWhat = '.{8}

(If you’re not familiar with GREP, you can do yourself a great favour by learning some of it .)

The question now is: What is myStory? How can a script see it? In your desktop version it’s the insertion point’s or the selected text frame’s parent story. In ID Server we have no selections; but at spill.end we do have the spilled story. Though indirectly, because what the Engine provides is a text frame rather than a story, but if you have a text frame you automatically have its parent story. The relevant Engine property is:

Let’s look at this in some detail. The Typefi Engine is a large collection of properties and functions, all subsumed under the global variable TYPEFI . This variable has scope over the whole JavaScript namespace. But, naturally, the TYPEFI object is available only when the Engine is running during a job, while we’re sitting here looking at an open document and a script in a script editor but without a running Engine.

What we need to do is to create our own TYPEFI object that matches the ‘real’ Engine but is triggered only when our script is running outside the Engine. When the script is running in a job, our own version of the Engine properties and functions should be ignored. We do that as follows:

We call this our interactive framework. The crucial test is in if (typeof TYPEFI == 'undefined') : it reads ‘if the TYPEFI object does not exist’. Therefore if we run this code on our desktop while we develop a script, the TYPEFI object is created on the fly, in this case with a single property. It’s a minimal framework, but it can be expanded to accommodate various things as we need them.

In this example, note that the Engine hands us the frame into which a story was spilled, not the spilled story itself. But when you have a text frame you also have its story, and our runt-prevention script can now be done as follows:

(function () { if (typeof TYPEFI == 'undefined') { TYPEFI = { inddSpillFrame: app.selection[0] } } app.findGrepPreferences = app.changeGrepPreferences = null; app.findGrepPreferences.findWhat = '.{8}

To try this in our document, we’ll run it interactively first so that we can catch and fix any problems. We could do that in a running job, but that’s just inefficient, it takes much longer. Then it’s time to test the script in a job. After uploading the script to the Typefi Server, we add it to the Spill end field in the Event Scripts tab of our Typefi workflow, and then run it.

Screenshot of a script in the Spill end field of a Typefi workflow.

Demo (Part II): Using a script framework (23:25)

We’ll call this code our interactive framework:

This is a modest framework with just one property, but you can add more as you need them. Let’s add a few that always come in handy: references to the active document and page, and some functionality for logging:

With this framework, TYPEFI.inddDocument is the active document, TYPEFI.inddPage is the active page, and inddSpillFrame we already know. Then there are three functions used for logging. The following line prints an info message in the Typefi job log when the script runs in a job:

When you run the script interactively, it prints the message in the ESTK’s console.

Again, I must stress that you must absolutely ensure that you don’t change any of the Engine’s properties while a job is running.

If over time your personal interactive framework grows, it might be cumbersome to copy it into your scripts all the time. You could place the code in a separate script file and link it into your event script, as follows:

Note the format of the file path: use forward slashes; and /d/ is the drive letter. This format works on both Mac and Windows. When you use this approach you should compile the scripts as a binary. The result is a script with the extension .jsxbin .

Conclusion (31:36)

The Typefi Engine’s properties and functions aren’t (yet) documented in a generally accessible way—we’re working on that. When in doubt, or when you have any questions, please post a query in our support forum .

This concludes our introduction of how scripts interact with the Engine. In the next episode we’ll turn to how scripts interact with the Typefi Designer plug-ins; in other words, the Typefi Document Object Model.

< Previous webinar |  Next webinar >

About Peter Kahrel

Peter was born in Amsterdam, the Netherlands. He trained as a linguist at the University of Amsterdam and has an MA and a PhD, specialising in syntax, semantics, and typology. He has lived in the UK since 1994, working as a typesetter, editor, copy-editor, and indexer (and sometimes as a designer too) for publishers in the UK, the Netherlands, and Germany, preparing for the press both books and journals. He combined this with teaching at the Linguistics Department at Lancaster University.

Peter has been programming InDesign with JavaScript since 2003, mainly to cut out the tedium that faces every typesetter and indexer but in equal measure because it’s good fun. Peter has worked as a script developer at Typefi since 2010, and is highly regarded in the global InDesign scripting community.

Check out Peter’s website—which includes a bunch of free scripts—at CreativePro .

  • Google Workspace
  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt
  • Apps Script

Google Sheets Macros

Google Sheets lets you record macros that duplicate a specific series of UI interactions that you define. Once you've recorded a macro, you can link it to a keyboard shortcut in the form Ctrl+Alt+Shift+Number . You can use that shortcut to quickly execute the exact macro steps again, typically in a different place or on different data. You can also activate the macro from the Google Sheets Extensions > Macros menu.

When you record a macro, Google Sheets automatically creates an Apps Script function (the macro function ) that replicates the macro steps. The macro function is added to an Apps Script project bound to the sheet, in a file titled macros.gs . In the event that there is already a project file bound to the sheet with that name, the macro function is appended to it. Google Sheets also automatically updates the script project manifest , recording the name and keyboard shortcut assigned to the macro.

Since every recorded macro is defined entirely within Apps Script, you can edit them directly within the Apps Script editor. You can even write macros from scratch in Apps Script, or take functions you've already written and turn them into macros.

Creating macros in Apps Script

You can take functions written in Apps Script and use them as macro functions. The easiest way to do this is by importing an existing function from the Google Sheets editor.

Alternatively, you can create macros within the Apps Script editor by following these steps:

  • In the Google Sheets UI, select Extensions > Apps Script to open the script bound to the sheet in the Apps Script editor.
  • Write the macro function. Macro functions should take no arguments and return no values.
  • Edit your script manifest to create the macro and link it to the macro function. Assign it a unique keyboard shortcut and name.
  • Save the script project. The macro is then available for use in the sheet.
  • Test the macro function in the sheet to verify that functions as intended.

Editing macros

You can edit macros attached to a sheet by doing the following:

  • In the Google Sheets UI, select Extensions > Macros > Manage macros .
  • Find the macro you want to edit and select more_vert > Edit macro . This opens the Apps Script editor to the project file containing the macro function.
  • Edit the macro function to change the macro behavior.

Importing functions as macros

If there is already a script bound to a sheet, you can import a function in the script as a new macro and then assign it a keyboard shortcut. You can do this by editing the manifest file and adding another element to the sheets.macros[] property.

Alternatively, follow these steps to import a function as a macro from the Sheets UI:

  • In the Google Sheets UI, select Extensions > Macros > Import .
  • Select a function from the list presented and then click Add function .
  • Select clear to close the dialog.
  • Select Extensions > Macros > Manage macros .
  • Locate the function you just imported in the list. Assign a unique keyboard shortcut to the macro. You can also change the macro name here; the name defaults to the name of the function.
  • Click Update to save the macro configuration.

Manifest structure for macros

The following manifest file example snippet shows the section of a manifest that defines Google Sheets macros. The sheets section of the manifest defines the name and keyboard shortcut assigned to the macro and the name of the macro function.

See the Sheets macro manifest resource for more details on how Sheets macro manifests are constructed.

Best practices

When creating or managing macros in Apps Script, it is recommended that you adhere to the following guidelines.

  • Macros are more performant when they are light-weight. Where possible, limit the number of actions a macro takes.
  • Macros are best suited for rote operations that need to be repeated frequently with little or no configuration. For other operations, consider using a custom menu item instead.
  • Always remember that macro keyboard shortcuts must be unique, and a given sheet can only have ten macros with shortcuts at any one time. Any additional macros can only be executed from the Extensions > Macros menu.
  • Macros that make changes to a single cell can be applied to a range of cells by first selecting the full range and then activating the macro. This means it is often unnecessary to create macros that duplicate the same operation across a predefined range of cells.

Things you can't do

There are a few restrictions on what you can do with macros:

Use macros outside bound scripts

Macros are defined in scripts bound to specific Google Sheets. Macro definitions are ignored if defined in a standalone script or web app .

Define macros in Sheets add-ons

You cannot distribute macro definitions using a Sheets add-on . Any macro definitions in a Sheets add-on project are ignored by users of that add-on.

Distribute macros in script libraries

You cannot distribute macro definitions using Apps Script libraries .

Use macros outside of Google Sheets

Macros are only a feature in Google Sheets, and do not exist for Google Docs, Forms, or Slides.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-03-05 UTC.

Kotlin Help

Get started with kotlin custom scripting – tutorial.

Kotlin scripting is the technology that enables executing Kotlin code as scripts without prior compilation or packaging into executables.

For an overview of Kotlin scripting with examples, check out the talk Implementing the Gradle Kotlin DSL by Rodrigo Oliveira from KotlinConf'19.

In this tutorial, you'll create a Kotlin scripting project that executes arbitrary Kotlin code with Maven dependencies. You'll be able to execute scripts like this:

The specified Maven dependency ( kotlinx-html-jvm for this example) will be resolved from the specified Maven repository or local cache during execution and used for the rest of the script.

Project structure

A minimal Kotlin custom scripting project contains two parts:

Script definition – a set of parameters and configurations that define how this script type should be recognized, handled, compiled, and executed.

Scripting host – an application or component that handles script compilation and execution – actually running scripts of this type.

With all of this in mind, it's best to split the project into two modules.

Before you start

Download and install the latest version of IntelliJ IDEA .

Create a project

In IntelliJ IDEA, select File | New | Project .

In the panel on the left, select New Project .

Name the new project and change its location if necessary.

From the Language list, select Kotlin .

Select the Gradle build system.

From the JDK list, select the JDK that you want to use in your project.

If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.

If you don't have the necessary JDK on your computer, select Download JDK .

Select the Kotlin or Gradle language for the Gradle DSL .

Click Create .

Create a root project for custom Kotlin scripting

Add scripting modules

Now you have an empty Kotlin/JVM Gradle project. Add the required modules, script definition and scripting host:

In IntelliJ IDEA, select File | New | Module .

In the panel on the left, select New Module . This module will be the script definition.

Name the new module and change its location if necessary.

From the Language list, select Java .

Select the Gradle build system and Kotlin for the Gradle DSL if you want to write the build script in Kotlin.

As a module's parent, select the root module.

Create script definition module

In the module's build.gradle(.kts) file, remove the version of the Kotlin Gradle plugin. It is already in the root project's build script.

Repeat previous steps one more time to create a module for the scripting host.

The project should have the following structure:

Custom scripting project structure

You can find an example of such a project and more Kotlin scripting examples in the kotlin-script-examples GitHub repository .

Create a script definition

First, define the script type: what developers can write in scripts of this type and how it will be handled. In this tutorial, this includes support for the @Repository and @DependsOn annotations in the scripts.

In the script definition module, add the dependencies on the Kotlin scripting components in the dependencies block of build.gradle(.kts) . These dependencies provide the APIs you will need for the script definition:

Create the src/main/kotlin/ directory in the module and add a Kotlin source file, for example, scriptDef.kt .

In scriptDef.kt , create a class. It will be a superclass for scripts of this type, so declare it abstract or open .

This class will also serve as a reference to the script definition later.

To make the class a script definition, mark it with the @KotlinScript annotation. Pass two parameters to the annotation:

fileExtension – a string ending with .kts that defines a file extension for scripts of this type.

compilationConfiguration – a Kotlin class that extends ScriptCompilationConfiguration and defines the compilation specifics for this script definition. You'll create it in the next step.

Define the script compilation configuration as shown below.

The configureMavenDepsOnAnnotations function is as follows:

You can find the full code here .

Create a scripting host

The next step is creating the scripting host – the component that handles the script execution.

In the scripting host module, add the dependencies in the dependencies block of build.gradle(.kts) :

Kotlin scripting components that provide the APIs you need for the scripting host

The script definition module you created previously

Create the src/main/kotlin/ directory in the module and add a Kotlin source file, for example, host.kt .

Define the main function for the application. In its body, check that it has one argument – the path to the script file – and execute the script. You'll define the script execution in a separate function evalFile in the next step. Declare it empty for now.

main can look like this:

Define the script evaluation function. This is where you'll use the script definition. Obtain it by calling createJvmCompilationConfigurationFromTemplate with the script definition class as a type parameter. Then call BasicJvmScriptingHost().eval , passing it the script code and its compilation configuration. eval returns an instance of ResultWithDiagnostics , so set it as your function's return type.

Adjust the main function to print information about the script execution:

You can find the full code here

Run scripts

To check how your scripting host works, prepare a script to execute and a run configuration.

Create the file html.scriptwithdeps.kts with the following content in the project root directory:

It uses functions from the kotlinx-html-jvm library which is referenced in the @DependsOn annotation argument.

Create a run configuration that starts the scripting host and executes this file:

Open host.kt and navigate to the main function. It has a Run gutter icon on the left.

Right-click the gutter icon and select Modify Run Configuration .

In the Create Run Configuration dialog, add the script file name to Program arguments and click OK .

Scripting host run configuration

Run the created configuration.

You'll see how the script is executed, resolving the dependency on kotlinx-html-jvm in the specified repository and printing the results of calling its functions:

Resolving dependencies may take some time on the first run. Subsequent runs will complete much faster because they use downloaded dependencies from the local Maven repository.

What's next?

Once you've created a simple Kotlin scripting project, find more information on this topic:

Read the Kotlin scripting KEEP

Browse more Kotlin scripting examples

Watch the talk Implementing the Gradle Kotlin DSL by Rodrigo Oliveira

7 Simple Windows Scripts to Save You Time and Effort

Want to take shortcuts in Windows? Or curious about taking your first steps into scripting? Here are seven Windows scripts to get started with.

For a beginner, getting into scripting can be very intimidating. However, there are some major benefits to using scripts on your Windows 10 PC. If you're just getting started, using Windows scripts written by others can often give you a good idea of how things work.

To learn scripting step-by-step, take a look at the simple Windows scripts featured in this article, and go from there. Figure out how they work. Think about how you might tweak them for yourself. Once you're comfortable with what a script is, you can think about diving into the nitty-gritty of coding .

Scripting With PowerShell

Many Windows users know PowerShell as a command line interface . However, we can also use PowerShell commands to create a script that we can call upon at a later date.

1. Shut Down Your Computer

You can shut down a Windows 10 PC with just a couple of clicks, but is that fast enough? By implementing a PowerShell script, we can place a shut down button anywhere on our desktop. Furthermore, we can learn how to make a script shortcut at the same time.

Open up Notepad and type out the following:

Next, click File > Save As .

Name the file shutdown.cmd and use the Save as type dropdown to select All Files . Run this file with administrator privileges, and your PC will shut down instantly.

By tweaking this script slightly, we can schedule a restart on a timer. To do so, make the following edit to your .cmd file:

The above will make your PC restart after a period of 60 seconds has elapsed. The -r in place of the -s we used above prompts the restart, while the -t tag stipulates the time. Feel free to tweak the integer to set a different span of time.

2. Remove Pre-Installed Windows 10 Apps

There are many benefits to installing Windows 10, but it's fair to say that the operating system (OS) comes packaged with several apps that qualify as bloatware . Rather than removing each of these pieces of software manually, we can set up a script that does the job for us.

Before you use this technique to get rid of any apps from your user account, consider the consequences. Many programs and services do important work behind the scenes, so don't be flippant about what you remove.

Open up a PowerShell window as an administrator and use this command to remove a particular app:

You'll need to find the name that Windows uses to refer to each individual app and insert it in place of APPNAME. For instance, this command would remove three commonly unwanted programs:

If you're in charge of setting up an entire fleet of computers, this can really speed up the process. Simply figure out which apps you want to remove, write up a script that gets rid of the lot, and run it on each PC.

3. Rename a Batch of Files

So you've just uploaded an album of photographs to your computer? And they're all labelled with whatever naming convention your camera uses by default? Wouldn't it be handy if you could attach a keyword that you can search for at a later date?

A simple PowerShell script can do just that. Enter the following to rename files en masse:

There are a few things to tweak before you run this script. First, adjust the path so it points toward the desired folder. Check which format your images are in, and change the file type in the second line if necessary. Finally, replace "IMG" in the last line with the text you want to replace, and "HOLIDAY2016" with the text you want to sub in.

If you upload images to your PC on a regular basis, it's worth saving this command as a CMD file, as explained above. When you need to use it again, open the file with Notepad , update it for the task at hand, then run it.

However, use caution when you're working with a script like this one. It doesn't take long for the command to rename every single file in a folder -- and that can cause big problems if it's pointed toward the wrong directory.

Scripting With AutoHotKey

We can do a lot with PowerShell — but it's not the only tool available to Windows users who are interested in writing their own scripts. AutoHotKey is one of several third-party programs that you can use to create custom scripts that go beyond the limits of the tools that come packaged with Windows 10.

Before we start putting together any handy AutoHotKey scripts, you need to download the software here . Install the package and then open up the program. To start working on a new script, simply right-click your desktop and select New > AutoHotKey Script . Rename the file, then open it up with Notepad or a similar text editor.

4. Open a Folder in an Instant

We all have folders that we return to on a regular basis. Sometimes it's convenient enough to place them on our desktop, but sometimes it would be even better if we could enter a keyboard shortcut to open it up while we're working on a separate task.

AutoHotKey allows you to set up a custom shortcut for any location on your computer. To do so, create a script that contains the following code:

To get this code to work, you'll need to replace "Brad" with your own Windows username. If you're new to AutoHotKey and that script looks like gibberish, don't fret — it's more straightforward than you might think.

The first part of the text stipulates the button combination that the user will need to use to execute the script, in our case the Windows key ( # ), the Shift key ( ^ ), and the D key. This shortcut is linked to the Run command we're trying to execute by a pair of colons.

5. Take Control of Your Virtual Desktops

Windows 10 introduced virtual desktops , a useful way of setting up distinct environments for different tasks. This functionality makes it easy to organize your workspace. However, switching between different desktops can be a little more unwieldy than a simple Alt-Tab.

Fortunately, there's an AutoHotKey script that allows you to immediately transfer to a different desktop using a simple keyboard shortcut. It also makes it easy to create and delete desktops as required. The code and an explanation of how the script works is available via GitHub .

6. Get System-Wide Autocorrect Functionality

Autocorrect isn't perfect, but it can be very handy if you're prone to the occasional spelling mistake. Some mobile operating systems like iOS deliver autocorrect functionality no matter what app you're using. You can get the same assistance on PC by implementing an AutoHotKey script.

You can grab a pre-built version of the script over at HowToGeek . However, it's well worth customizing the code to calibrate it for your usage. For instance, if you regularly use slang words, you'll want to make sure they don't get corrected erroneously.

7. Make Sure Sentences Start With a Capital Letter

If system-wide autocorrect seems too drastic, you might be better off with this tweak that counteracts a common typing error. Proper capitalization is a must if you want your writing to look professional, and you can use AutoHotKey to double-check your work for mistakes.

You can find the necessary code on the AutoHotKey forum . The script makes sure that any period, question mark, or explanation mark will be followed by a capital letter.

Next Steps in Scripting

The internet gives us access to a whole host of scripts developed by others that we can pick and choose from. That's great, but the most useful scripts are often the ones you create for yourself.

The scripts in this article perform tasks that don't require your oversight. These tasks will vary from user to user. A working knowledge of how scripts work is the first step towards making scripts that are tailored to your own usage.

Scripts you find online can certainly save you time and effort. However, if you take the time to really get to grips with tools like PowerShell and AutoHotKey, you might be surprised by what you can come up with.

Do you have another Windows script that you want to share with other users? Why not join the conversation in the comments section below?

How to create your own Photoshop scripts

Bored of doing the same repetitive tasks in Photoshop? Then create a script to automate it. We show you how, so you can free up your time for creativity...

If you’ve used Photoshop for more than a few months you’ll have no doubt come across actions - little pockets of wonderment that allow us to be free of identical tasks that are essential, but eat into our quality creative time. Actions are great (check out our selection of must-have actions for Photoshop here ), but they do have one serious limitation: they’re dumb, and can’t do anything more complicated than play back through the prescribed series of steps.

Thankfully, Adobe recognised this problem a long time ago, and added support for scripting to Photoshop and most of their other creative tools. Photoshop’s scripting engine allows you to write in Applescript, VBScript or JavaScript , and perform complex operations that would normally require human intervention.

Your Scripts can do anything Photoshop can

So, what’s an example of something that a script can do that an action can’t? Well, take the very basic example of toggling a layer’s visibility on and off. An action can easily turn off the visibility of a layer (or turn it on), but it can’t toggle visibility intelligently. A script can determine the current visibility state of a given layer, then perform a different task according that state.

It’s this ability to make conditional decisions that sets scripts apart from actions, and makes them super-powerful. For some great examples of what you can do with scripts, see this list of the best free Photoshop scripts .

writing custom scripts

Naturally, creating scripts does require a little programming, but if you’re already familiar with JavaScript you’ll find it very easy to get started. To make it a little less painful, Adobe has thoughtfully created a scripting manual, along with some excellent sample scripts.

Versions of Photoshop

If you’re using a version of Photoshop earlier than CS5, the scripting guide is available in your Application > Photoshop > Scripting folder. If you’re using CS6, you’ll find that this isn’t installed by default - you’ll need to download it here . You can also find complete script reference guides at the same place.

Once you feel comfortable with scripting you’ll be able to automate many functions within Photoshop, whether it’s creating 1000 web images or automatically generating meta data with your copyright notifications.

Get the Creative Bloq Newsletter

Daily design news, reviews, how-tos and more, as picked by the editors.

Action or Script?

When deciding whether a task requires an action or a script, the golden mantra to remember is that actions are great for performing identical tasks over and over again.

Scripts allow you to create a custom, conditional result which is ideal for similar but non-identical tasks.

Make your own script

writing custom scripts

You can create your script in Textpad or Notepad. You'll find a full reference guide in the Photoshop install directory called 'Scripting Guide'. You’ll also find some sample scripts in this directory.

Using JavaScript as the scripting language (Photoshop also supports Visual Basic and AppleScript) will ensure your script works across both PCs and Macs. We’re going to create a script that just pops up a message to illustrate the point.

Save the document as testscript.jsx if you are using CS2, or testscript.js for CS3 and above

Enter the following text into your text editor:

Save the document as testscript.jsx if you are using Photoshop CS2, or testscript.js if you are using Photoshop CS3 and above.

writing custom scripts

In Photoshop, open a document you’re working on. Select File > Scripts > Browse and locate your script (or one of the sample scripts if you haven’t plucked up the courage to create your own yet).

All being well, your script will open and execute. If you’re using the sample script above, you’ll see a dialogue box appear with some text and a button.

Clicking on the button will simply pop-up a message, but you can have Photoshop perform all manner of tasks when the button is pressed. This is where the real power of scripting shows itself. Your scripts can do anything Photoshop can - apply filters, resize documents, show or hide layers, add adjustment layers as well as save and export documents.

Set up an event-based script

Scripts (and actions) can be executed automatically by Photoshop when a particular event fires. These events can include opening Photoshop, creating a new document, printing and many more. Event-based scripts are an ideal way to deal with common tasks you commonly perform time after time, based on the specific event. For example, you might want to edit the metadata for your file when you first create it. Using an event-based script, you can have the file info panel pop-up as soon as you create a new document.

Setting up an event-based script is really easy - follow our step-by-step guide below:

Start by creating the script you’d like to execute, or have a look at some of the sample scripts Adobe has provided.

Open the event-based scripts manager by choosing File > Scripts > Script Events Manager. Once the dialog box is open, check the Enable Events to Run Scripts/Actions checkbox.

Select the event from the Photoshop Event drop-down list. If you can’t see the precise event you’d like to capture, check out the scripting reference guide for details on how to add your own events based on Photoshop’s internal event listeners.

Choose your script, or select from one of the presets included in the drop-down list of scripts. If you’d rather run an action based on this event, choose the 'action' radio button instead and browse your list of available actions.

Click the Done button to close the Script Events Manager, or the Add button if you’d like to add additional event-based scripts.

Words : Sam Hampton-Smith

Liked this? Read these!

  • Adobe Photoshop CS6 hands-on review
  • Free Photoshop brushes
  • The best Photoshop plugins

Have you seen some great Photoshop scripts, or have you created your own worth sharing? Let us know in the comments below!

Thank you for reading 5 articles this month* Join now for unlimited access

Enjoy your first month for just £1 / $1 / €1

*Read 5 free articles per month without a subscription

Join now for unlimited access

Try first month for just £1 / $1 / €1

The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan , Deputy Editor Rosie Hilder , Ecommerce Editor Beren Neale , Senior News Editor Daniel Piper , Editor, Digital Art and 3D Ian Dean , Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear , as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq. 

Related articles

Obviously, Samsung's mocking Apple's controversial iPad Pro ad

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications
  • Writing custom scripts

The previous section described how scripts can be used to automate analysis within QuPath, and apply it in a high-throughput manner across many images within a project.

Note on versions This documentation is for QuPath v0.1.2 (the latest stable release at the time of writing). It has not yet been updated for v0.2.0 (still in development).

In principle, scripts in this case aren't actually needed to get the final result - it would be possible to run all the commands for every image manually, and end up at the same place. The benefit of scripting is that it makes the process a lot less manual, a lot faster, and a lot more reproducible - no longer undermined by a lapse in concentration leading to an errant mouse-click.

However, this isn't the only purpose of scripting within QuPath. Scripts can also be used to access far more features, and to be able to customize the analysis in far greater ways to ensure that it answers the right questions. Often, a tiny script - just two or three lines long - can already be enormously useful in getting the results just right.

This section describes a bit more of the technical background needed to make sense of QuPath's scripts.

QuPath scripts are Groovy

The scripts produced by QuPath are created for a particular programming language: Groovy . This was chosen because Groovy has a huge range of features, while closely matching the Java programming language in which the majority of QuPath itself is written. Programmers familiar with Java (or similar ) languages should have little trouble learning Groovy quickly, while someone new to programming can also pick it up due to its support for lots of shortcuts and user-friendly features.

Other scripting languages
It's also possible to scripting languages other than Groovy. To switch to Javascript , simply open the Script Editor and select Language → Javascript . The information here might be useful to understand how Javascript works with Java.
Alternatively, the Data exchange contains information on how to use QuPath with Python , MATLAB or the ImageJ macro language .

Simple scripts with the Script Editor

This section describes with examples how some simple scripts can be created directly using QuPath's Script Editor .

To follow along, ideally you should open an image and create several annotation and detect and classify some cells. The Detecting objects and Classifying objects sections give more details on how to do this.

Counting all objects

The first, manually-written script here simply counts up the number of objects - of any type - within an image (or, more exactly, inside the Object hierarchy associated with an image).

To run it, simply open the Script Editor ( Automate → Show script editor ), type in the following code, and choose Run → Run .

This section does not try to explain all the principles of scripting, or programming in general - a bit of googling can find many tutorials for this. So here we focus on the specifics of scripting in QuPath, after the following three points of introduction:

  • do something
  • sometimes require extra information (provided between the parentheses), and
  • sometimes return a result.
  • n is a variable . It represents the result of whatever nObjects() returns, i.e. the number of objects in the image. = is the assignment operator that makes this happen.
  • Text is referred to as a string . Strings are created by putting text inside double quotes (or, optionally, in single quotes). It is possible to make a longer string by concatenating parts using the + operator.
Finding methods
It can be troublesome to know what methods are available, or how exactly they should be typed.
To help, QuPath's Script Editor has a very rudimentary auto-complete function. To use it, type the first letter (or first few letters) of a possible method name, and press Ctrl + space . QuPath will then fill in the rest of any method that it knows about. Pressing Ctrl + space repeatedly will cause QuPath to cycle through any alternatives that also start with the same letters.

Counting objects of different types

It might be desirable to be a bit more specific than simply counting all objects. If so, the following script can count up the number of detection and annotation objects separately:

Things get more interesting whenever we start to 'loop' through objects of particular types, and then to do things with them.

For example, this script loops through all the annotation objects and prints out a representation of the object.

To learn more about for loops in Groovy, see the documentation here .
Warning! Printing all detection objects is generally not a good idea, since there may be many very detections - and printing many thousands of lines can be very slow.

Alternatively, a representation of some particular property of the annotation could be printed instead. The following script prints the ROI, rather than the object itself:

And this script prints the classification:

Counting classifications

One application building on the above scripts would be to count up the number of detections with a specific classification. To do so, we first need to get a reference to the classification, and then check if this matches with the classification of the detection.

The following script shows one way to do this, for 'Tumor' classifications.

However, depending upon what the outcome should be, there might be a subtle problem with this script. This is because it will only count up detections that have exactly the classification 'Tumor' - but not the derived classifications 'Tumor: Positive' or 'Tumor: Negative' , for example.

See Object classifications for more detail on classifications and derived classifications.

If the script should count up all detections classified as 'Tumor' - including those that also have a more specific derived classification - then it could be modified as follows:

By using the isAncestorOf method built-in to each classification, a check is performed to see whether the classification of the object is either equal to or derived from the tumor classification. The method returns true if either of these is the case.

If derived classifications were not used, the two scripts give the same results. Therefore for most applications it is safest to use the more exact second script, and test for ancestry - since that is likely to be what is expected.

The way classifications are represented is very QuPath-specific, and it is not immediately obvious why isAncestorOf should work - or even that the method exists.
However, please don't let this put you off scripting. It is important to be aware that such gotchas exist, however the situation is not hopeless. The Advanced scripting with IntelliJ section shows you how you can set things up to be able to quickly check the QuPath source code to find out how things are implemented and what methods are available. It should also be evident when looking carefully at the output of a script when something has gone wrong.
Therefore, the tools exist to help find out this kind of thing. And there are also a variety of ways to get help and ask questions, as described in the Getting help section.

Calculating percentages

Using a small modification of the last script, it is possible to then also count up the non-tumor classifications and determine proportions or percentages, e.g.

Adding areas

In some cases, it might be useful to add up the areas of the detections for each class. The following code does this:

Note that this script does not output the absolute values of the areas. This is because, by default, the area values will be given in pixels. Therefore percentages can still be meaningful, but absolute values may be misleading unless they are scaled by the pixel sizes.

Of course, it's possible to get the pixel sizes in a script as well... but that's for another tutorial, or a discussion forum question.

Technical notes

The following notes are not essential for anyone new to scripting, or just wanting to use it within QuPath. Rather, they are intended for anyone who wants to know more about how it is designed and works under the hood.

Default methods & imports

In the tutorial above, several methods were used that are QuPath-specific and not normally available in Groovy (or other scripting languages) - yet there was no need to declare or import them anywhere.

This makes writing scripts in QuPath somewhat like using a customized macro language, rather than simply using 'plain' Groovy. This purpose of this is to try to help users unfamiliar with scripting to be able to solve useful problems with a minimum of fuss.

However, a natural question would be: where do these default methods come from, and how does QuPath know they are there?

Static methods in QP & QPEx

To answer the first part of the question, the default methods are implemented in one of two Java classes:

Clicking on the links above should open the source code, allowing the methods to be seen in more detail.

QP.java contains methods that do not depend upon the user-interface, while QPEx.java contains all the same methods - plus a few more that do depend on the user-interface.

Does this distinction matter when writing a simple script? Probably not, but it is made to try to help make most QuPath scripts still work in scenarios where the user interface may not be available. If you don't care about this, just use QPEx.java . It extends from QP.java , which means that it includes everything that QP.java does.

The use of static methods has some troublesome limitations in terms of maintainability (particular with regard to subclassing), so the implementation underpinning this approach may change in the future... although any changes that are made will hopefully remain backwards-compatible.

Importing the static methods

To answer the second part of the question above, QuPath knows about the methods in QP and QPEx because they are imported automatically for every script that is run through the Script Editor . Furthermore, the variables returned by getCurrentImageData() and getCurrentHierarchy() are set appropriately, depending upon what image is active at the time.

However, it may be important to note that this is only true so long as Run → Include default bindings is selected (it is by default). Turning this setting off means that QuPath will not import the methods are set the variables. This tends to result in scripts needing to be longer and more complicated, with more import statements - but may be useful if the default imports are found to somehow conflict with a script that is being written.

If you want to import QP or QPEx manually, then you need to add one or both of these lines to the top of your script:

From QuPath v0.2.0-1, QPEx is under qupath.lib.gui.scripting.QPEx .

These docs are for QuPath ≤ v0.1.2.

For more up-to-date information, see https://qupath.readthedocs.io

  • What is QuPath?
  • System requirements
  • Supported image formats
  • Installing QuPath
  • Citing QuPath
  • Getting started
  • Video tutorials
  • First steps
  • Viewing images
  • Drawing regions
  • Counting cells
  • Multiple images
  • Preferences
  • Getting help
  • Introduction to analysis
  • Image fundamentals
  • Detecting objects
  • Classifying objects
  • Exporting results
  • Sample applications
  • TMA CD3 analysis
  • TMA ER analysis
  • Spot detection
  • Tissue section analysis
  • QuPath concepts
  • Object-oriented analysis
  • Types of object
  • Object measurements
  • Object classifications
  • Object hierarchies
  • Working with objects
  • From workflows to scripts
  • Advanced scripting with IntelliJ
  • Scripting examples
  • Data exchange
  • Working with ImageJ
  • Working with MATLAB
  • Working with Python
  • Working with Weka
  • QuPath for Developers
  • QuPath architecture
  • Important Java classes
  • Creating extensions
  • Writing an ImageServer
  • Changing colors
  • Paths and configuration
  • Project structure
  • Tissue Microarrays
  • Viewer tracking
  • Troubleshooting
  • Tips and tricks
  • Fluorescence handbook
  • A note on version numbers
  • Preprocessing
  • Region identification
  • Calculate features
  • Cell analysis
  • Classification
  • Shortcut keys

Clone this wiki locally

CAD Tutorials and Best Practices for professionals and students

Learn how to write command scripts for AutoCAD and automate your plotting

March 14, 2012 by Paul Munford 64 Comments

In this Article...

One of the great benefits of using AutoCAD to create your technical drawings is the ability to adapt AutoCAD to suit your company’s processes. If you can establish a technical drawing process that you perform frequently – you can automate it with AutoCAD. If you’ve ever had to do the same thing with AutoCAD twice – think about how you could automate it so you never have to do it again.

One of the easiest ways to automate a process within AutoCAD is to write a script. In this post, I will demonstrate how to write and develop a script for AutoCAD. In this example we will write a script that will automate a typical plot routine.

What is a script?

In computer programming terms, a script is a programme that will run with no interaction from the user. To AutoCAD, a script file is an ASCII text file that contains a set of command line instructions for AutoCAD to follow – just like an actor reading from a script. AutoCAD script files always have a file extension of ‘.scr’.

Defining a process

Before we can automate a process, first we have to define it. In this example we will write a script file that will create an A1 PDF plot of a drawing. We will work through the instructions that we would usually need to give AutoCAD to make a plot, and make a note of them so that we can write it up into a script.

Recording the steps

AutoCAD script files cannot interact with dialogue boxes, so we need to work out what we would type at the command line to produce our plot. To this end we will use the command line version of the plot command ‘-PLOT’ (the hyphen suppresses the plot dialogue) and we will manually step through the options to produce our plot.

Tip: If you don’t know the answer to the question AutoCAD is asking you, type ‘?’ at the command line and hit return to see a list of available options. Copy these options out into a text file for later reference. You may have to step through the routine a few times to get all the answers you need.

When we have produced a plot manually, we can open up the text window (hit F2 on your keyboard) to review the steps.

The plot script in the AutoCAD text window

Creating the script file

The next step is to open a new blank notepad file (Please don’t be tempted to use Word or another word processing programme for this!). Copy the commands from the AutoCAD text window, and paste them into your notepad file.

Editing out the Junk

The next step is to edit out what you don’t need.

You don’t need AutoCAD’s command line prompts. You do need your replies. In the image below I have highlighted what can be stripped out. An empty line is equivalent to you pressing ‘Return’ on your keyboard, so leave those empty lines in!

Watch out for character wrapping inherited from the AutoCAD text window. Make sure all the text for each step is on the same line.

The unedited plot script in a text file

You should end up with something that looks like this:

The Edited plot script in a text file

Don’t forget that you will need an empty line at the end of your script. This is equivalent to pressing ‘Return’ to complete the command.

Testing the script

The next step is to test the script. First, close down the text file and change the file extension to ‘.scr’

Tip: make sure that Windows is showing file extensions before you do this!

Next, simply drag and drop your Script file into AutoCAD to run it.

Dragging a SCR script file into AutoCAD

It may take you a couple of goes to get your script to run. Use the text window to see how far your script ran before it stalled. Make the corrections in the .scr file and keep trying until you are happy!

Adding Comments (putting some junk back in)

Now you have a running script file it is a good idea to add a few comments to remind you what you did. You never know, it might be you who has to re-write the script in six months time…

AutoCAD will ignore any line in your script file that is preceded by a semi-colon. My version of the script ended up looking like this:

The finished AutoCAD Plotting script

How could you use AutoCAD Scripting to automate your workflow?

AutoCAD scripts can be used to automate many tasks. You could use a script to add your corporate standard layers or styles to a drawing. You could write a script to update your title block. And of course you could adapt the script we’ve just finished writing to automate many of your plotting tasks.

AutoCAD scripts also work for AutoCAD LT, and you can run scripts on a whole batch of drawings using a windows .bat file or by using the free Scriptpro program from Autodesk labs .

Next time we will look at the differences between scripts and Macros .

Until then – stay lucky.

' src=

New on CADnotes

  • Free Dynamo Graph: Auto Dimensions from Grids and Walls
  • How to: Use Dynamo Graph in Dynamo Player
  • Model-Based Progress Tracking in Autodesk Build
  • Understanding Surface and Cut Patterns in Revit
  • Revit 2024.1 Update is Released

Meet the Authors

avatar for

Get Connected

CADnotes on Facebook

Shell Scripting for Beginners – How to Write Bash Scripts in Linux

Zaira Hira

Shell scripting is an important part of process automation in Linux. Scripting helps you write a sequence of commands in a file and then execute them.

This saves you time because you don't have to write certain commands again and again. You can perform daily tasks efficiently and even schedule them for automatic execution.

You can also set certain scripts to execute on startup such as showing a particular message on launching a new session or setting certain environment variables.

The applications and uses of scripting are numerous, so let's dive in.

In this article, you will learn:

  • What is a bash shell?
  • What is a bash script and how do you identify it?
  • How to create your first bash script and execute it.
  • The basic syntax of shell scripting.
  • How to see a system's scheduled scripts.
  • How to automate scripts by scheduling via cron jobs.

The best way to learn is by practicing. I highly encourage you to follow along using Replit . You can access a running Linux shell within minutes.

Introduction to the Bash Shell

The Linux command line is provided by a program called the shell. Over the years, the shell program has evolved to cater to various options.

Different users can be configured to use different shells. But most users prefer to stick with the current default shell. The default shell for many Linux distros is the GNU Bourne-Again Shell (bash). Bash is succeeded by Bourne shell ( sh ).

When you first launch the shell, it uses a startup script located in the .bashrc or .bash_profile file which allows you to customize the behavior of the shell.

When a shell is used interactively, it displays a $ when it is waiting for a command from the user. This is called the shell prompt.

[username@host ~]$

If shell is running as root, the prompt is changed to # . The superuser shell prompt looks like this:

[root@host ~]#

Bash is very powerful as it can simplify certain operations that are hard to accomplish efficiently with a GUI. Remember that most servers do not have a GUI, and it is best to learn to use the powers of a command line interface (CLI).

What is a Bash Script?

A bash script is a series of commands written in a file. These are read and executed by the bash program. The program executes line by line.

For example, you can navigate to a certain path, create a folder and spawn a process inside it using the command line.

You can do the same sequence of steps by saving the commands in a bash script and running it. You can run the script any number of times.

How Do You Identify a Bash Script?

File extension of .sh ..

By naming conventions, bash scripts end with a .sh . However, bash scripts can run perfectly fine without the sh extension.

Scripts start with a bash bang.

Scripts are also identified with a shebang . Shebang is a combination of bash # and bang !  followed the the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.

Below is an example of the shebang statement.

The path of the bash program can vary. We will see later how to identify it.

Execution rights

Scripts have execution rights for the user executing them.

An execution right is represented by x . In the example below, my user has the rwx (read, write, execute) rights for the file test_script.sh

image-98

File colour

Executable scripts appear in a different colour from rest of the files and folders.

In my case, the scripts with execution rights appear as green.

image-99

How to Create Your First Bash Script

Let's create a simple script in bash that outputs Hello World .

Create a file named hello_world.sh

Find the path to your bash shell..

image-100

In my case, the path is /usr/bin/bash and I will include this in the shebang.

Write the command.

We will echo "hello world" to the console.

Our script will look something like this:

Edit the file hello_world.sh using a text editor of your choice and add the above lines in it.

Provide execution rights to your user.

Modify the file permissions and allow execution of the script by using the command below:

chmod modifies the existing rights of a file for a particular user. We are adding +x to user u .

Run the script.

You can run the script in the following ways:

./hello_world.sh

bash hello_world.sh .

Here's the output:

Two ways to run scripts

The Basic Syntax of Bash Scripting

Just like any other programming language, bash scripting follows a set of rules to create programs understandable by the computer. In this section, we will study the syntax of bash scripting.

How to define variables

We can define a variable by using the syntax variable_name=value . To get the value of the variable, add $ before the variable.

image-104

Tux is also the name of the Linux mascot, the penguin.

Hi, I am Tux.

Arithmetic Expressions

Below are the operators supported by bash for mathematical calculations:

Let's run a few examples.

Note the spaces, these are part of the syntax

Numerical expressions can also be calculated and stored in a variable using the syntax below:

var=$((expression))

Let's try an example.

image-109

Fractions are not correctly calculated using the above methods and truncated.

For decimal calculations , we can use bc command to get the output to a particular number of decimal places. bc (Bash Calculator) is a command line calculator that supports calculation up to a certain number of decimal points.

echo "scale=2;22/7" | bc

Where scale defines the number of decimal places required in the output.

Getting output to 2 decimal places

How to read user input

Sometimes you'll need to gather user input and perform relevant operations.

In bash, we can take user input using the read command.

To prompt the user with a custom message, use the -p flag.

read -p "Enter your age" variable_name

image-111

Numeric Comparison logical operators

Comparison is used to check if statements evaluate to true or false . We can use the below shown operators to compare two statements:

Let's compare two numbers and find their relationship:

image-112

Conditional Statements (Decision Making)

Conditions are expressions that evaluate to a boolean expression ( true or false ). To check conditions, we can use if , if-else , if-elif-else and nested conditionals.

The structure of conditional statements is as follows:

  • if...then...fi statements
  • if...then...else...fi statements
  • if..elif..else..fi
  • if..then..else..if..then..fi..fi.. (Nested Conditionals)

To create meaningful comparisons, we can use AND -a and OR -o as well.

The below statement translates to: If a is greater than 40 and b is less than 6.

if [ $a -gt 40 -a $b -lt 6 ]

Example : Let's find the triangle type by reading the lengths of its sides.

Test case #1

image-113

Test case #2

image-114

Test case #3

image-115

Looping and skipping

For loops allow you to execute statements a specific number of times.

Looping with numbers:

In the example below, the loop will iterate 5 times.

Looping-with-numbers

Looping with strings:

We can loop through strings as well.

Looping-with-strings

While loops check for a condition and loop until the condition remains true . We need to provide a counter statement that increments the counter to control loop execution.

In the example below, (( i += 1 )) is the counter statement that increments the value of i .

image-153

Reading files

Suppose we have a file sample_file.txt as shown below:

image-151

We can read the file line by line and print the output on the screen.

Lines with line number printed

How to execute commands with back ticks

If you need to include the output of a complex command in your script, you can write the statement inside back ticks.

var= ` commands `

Example : Suppose we want to get the output of a list of mountpoints with tmpfs in their name. We can craft a statement like this: df -h | grep tmpfs .

To include it in the bash script, we can enclose it in back ticks.

image-118

How to get arguments for scripts from the command line

It is possible to give arguments to the script on execution.

$@ represents the position of the parameters, starting from one.

Run it like this:

./script arg1 arg2

image-155

How to Automate Scripts by Scheduling via cron Jobs

Cron is a job scheduling utility present in Unix like systems. You can schedule jobs to execute daily, weekly, monthly or in a specific time of the day. Automation in Linux heavily relies on cron jobs.

Below is the syntax to schedule crons:

Here, * represents minute(s) hour(s) day(s) month(s) weekday(s), respectively.

Below are some examples of scheduling cron jobs.

You can learn about cron in detail in this blog post.

How to Check Existing Scripts in a System

Using crontab.

crontab -l lists the already scheduled scripts for a particular user.

My scheduled scripts

Using the find command

The find command helps to locate files based on certain patterns. As most of the scripts end with .sh , we can use the find script like this:

  • . represents the current directory. You can change the path accordingly.
  • -type f indicates that the file type we are looking for is a text based file.
  • *.sh tells to match all files ending with .sh .

image-159

If you are interested to read about the find command in detail, check my other post .

Wrapping up

In this tutorial we learned the basics of shell scripting. We looked into examples and syntax which can help us write meaningful programs.

What’s your favorite thing you learned from this tutorial? Let me know on Twitter !

You can read my other posts here .

Work vector created by macrovector - www.freepik.com

I am a DevOps Consultant and writer at FreeCodeCamp. I aim to provide easy and to-the-point content for Techies!

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

IMAGES

  1. How to Write a Script (Step-by-Step Guide)

    writing custom scripts

  2. How to Format a Script

    writing custom scripts

  3. How to Write a Script: A Beginner's Guide

    writing custom scripts

  4. How to write an animation script (5 simple steps) + extra tips

    writing custom scripts

  5. How to write a script

    writing custom scripts

  6. Scripts How To Write Them For Passion And Money

    writing custom scripts

VIDEO

  1. How I Would Learn YouTube Scriptwriting (If I Could Start Over)

  2. Pooh's Adventures of Disney's Recess: School's Out Draft (for @ThomasLover-fr8nh)

  3. PiStation

  4. How to write scripts for YouTube FAST

  5. FiveM: GTA V

  6. FiveM: GTA V

COMMENTS

  1. Fundamentals of Apps Script with Google Sheets #1: Macros & Custom

    A macro is a series of recorded actions within Google Sheets. Once recorded, you can activate a macro to repeat those actions later with a menu item or shortcut key. You can both create and update your own macros in both Google Sheets and the Apps Script code editor. In the Apps Script code editor, you can also create custom functions.

  2. Custom Functions in Google Sheets

    Creating a custom function. To write a custom function: Create or open a spreadsheet in Google Sheets. Select the menu item Extensions > Apps Script. Delete any code in the script editor. For the DOUBLE function above, simply copy and paste the code into the script editor. At the top, click Save save. Now you can use the custom function.

  3. Custom Script: Use Cases & Best Practices

    A Custom Script is a piece of code that is specifically written to perform a particular task or fulfill a unique requirement. Unlike pre-built scripts, which are more generic and standardized, custom scripts offer the flexibility to tailor the code to your specific needs. With custom scripts, you can truly take control and craft solutions that ...

  4. Mastering Google Apps Script: A Comprehensive Guide

    Google Apps Script is a powerful cloud-based scripting language developed by Google. It allows users to extend the functionality of various Google Workspace applications, such as Google Docs, Sheets, Slides, Forms, and Gmail, by writing custom scripts. Which Google Workspace apps does Google Apps Script support?

  5. Deep dive into package.json scripts

    Writing custom scripts. Alright so now that we have a firm grasp of how scripts work let us explore how we can write our scripts to do some cool stuff. I will be writing both a js/ts version in this guide so you can fully understand what the differences are and what you need to do in each scenario.

  6. Google Sheet Script Editor: How to Master It in Simple Steps

    Step 1: Open the Script Editor. Open your Google Sheet and click on "Extensions" in the menu, then select "Apps Script.". When you open the Script Editor for the first time, you'll see a blank project. This is where you'll write your code. The editor is based on JavaScript, so if you're already familiar with that language, you ...

  7. SmartScripter

    SmartScripter is an AI-driven web application designed for script generation in multiple programming languages. Including Excel VBA, Google Apps Script, Basic JavaScript, React.js, Bash, PowerShell, SQL, and Python. The platform's goal is to streamline workflows, automate repetitive tasks, and enhance productivity through an intuitive interface ...

  8. Allow or prevent custom script

    Administrators can control custom script settings for a specific site; deciding if they want to allow or block custom script on a specific site: By default, any changes to custom script settings for a specific site only last for a maximum of 24 hours. After that time, the setting will reset to its original value for that specific site.

  9. How do I add a custom script to my package.json file that runs a

    I want to be able to execute the command script1 in a project directory that will run node script1.js.. script1.js is a file in the same directory. The command needs to be specific to the project directory, meaning that if I send someone else the project folder, they will be able to run the same command.

  10. YouMeScript: screenplays in Google Drive

    YouMeScript is screenwriting for Google Drive. Easily write perfectly formatted film-scripts and screenplays, with full realtime collaboration. Import and export popular formats. Free and upgradable.'

  11. netbox/docs/customization/custom-scripts.md at develop

    Custom scripts enable the user to directly and conveniently manipulate NetBox data in a prescribed fashion. They can be used to accomplish myriad tasks, such as: They can also be used as a mechanism for validating the integrity of data within NetBox. Script authors can define test to check object against specific rules and conditions. For ...

  12. Editor Scripting

    The complete solution for professionals to create, operate and monetize. Track your progress and get personalized recommendations. Editor Scripting can help you customize and extend the Unity editor to make it easier to use on your projects. This tutorial covers the basics of editor scripting, including building custom inspectors, gizmos, and ...

  13. How to write and use custom InDesign scripts

    When you start writing a script, the first question you ask is at which script event the script should run. Well, since this script doesn't rely on geometry, and since it can change the text flow, the best moment is at spill.end .

  14. Google Sheets Macros

    In the Google Sheets UI, select Extensions > Apps Script to open the script bound to the sheet in the Apps Script editor. Write the macro function. Macro functions should take no arguments and return no values. Edit your script manifest to create the macro and link it to the macro function. Assign it a unique keyboard shortcut and name.

  15. Get Started with Airtable Custom Scripts

    Expand beyond the core Airtable functionality with custom scripts. Read on to learn more about scripting, explore some templates, and run your first script.

  16. Writing custom build scripts

    Write resilient scripts. Custom build scripts can perform critical tasks like installing dependencies or uploading build artifacts to storage. Write resilient code that handles errors gracefully, and, if a command fails, return a nonzero exit code. By returning a nonzero exit code in your custom build script, you let Xcode Cloud know that ...

  17. Get started with Kotlin custom scripting

    Select the Gradle build system and Kotlin for the Gradle DSL if you want to write the build script in Kotlin. As a module's parent, select the root module. Click Create. In the module's build.gradle(.kts) file, remove the version of the Kotlin Gradle plugin. It is already in the root project's build script.

  18. 7 Simple Windows Scripts to Save You Time and Effort

    To do so, make the following edit to your .cmd file: shutdown -r -t 60. The above will make your PC restart after a period of 60 seconds has elapsed. The -r in place of the -s we used above prompts the restart, while the -t tag stipulates the time. Feel free to tweak the integer to set a different span of time.

  19. How to create your own Photoshop scripts

    Step 03. In Photoshop, open a document you're working on. Select File > Scripts > Browse and locate your script (or one of the sample scripts if you haven't plucked up the courage to create your own yet). All being well, your script will open and execute. If you're using the sample script above, you'll see a dialogue box appear with ...

  20. Writing custom scripts · qupath/qupath Wiki · GitHub

    The first, manually-written script here simply counts up the number of objects - of any type - within an image (or, more exactly, inside the Object hierarchy associated with an image). To run it, simply open the Script Editor ( Automate → Show script editor ), type in the following code, and choose Run → Run.

  21. AutoCAD tip: how to write command scripts and automate plotting

    Recording the steps. AutoCAD script files cannot interact with dialogue boxes, so we need to work out what we would type at the command line to produce our plot. To this end we will use the command line version of the plot command '-PLOT' (the hyphen suppresses the plot dialogue) and we will manually step through the options to produce our ...

  22. Shell Scripting for Beginners

    Scripts start with a bash bang. Scripts are also identified with a shebang. Shebang is a combination of bash # and bang ! followed the the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.